wpf,visibility属性的多元素绑定及值转换

visibility实现多元素绑定。

实现多绑定转换

public class VisibilityConverter : IMultiValueConverter
{
  public object Convert(object[] values, Type targetType, object parameter, CultureInfo culture)
  {
    if (values.Length == 2 && values[0] != null && values[1] != null)
    {
      if ((values[0].ToString() + values[1].ToString()).Length > 10)
      {
        return Visibility.Visible;
      }
      else
      {
        return Visibility.Collapsed;
      }
    }
    else
    {
      return Visibility.Collapsed;
    }
  }

  public object[] ConvertBack(object value, Type[] targetTypes, object parameter, CultureInfo culture)
  {
    throw new NotImplementedException();
  }
}

 

使用资源style对元素设置visibility多元素绑定

<Window>
    <Window.Resource>
    <ResourceDictionary>
<ConvertTool:VisibilityConverter x:Key="VisibilityValueConvert" />
      <Style x:key="MultiBindingStyle" TargetType="TextBlock">
        <Setter Property="Visibility">
          <Setter.Value>
            <MultiBinding Converter="{StaticResource ResourceKey=VisibilityValueConvert}"><!--被使用的资源需在使用前定义-->
              <Binding ElementName="text1" Path="Text" />     
              <Binding ElementName="text2" Path="Text" />
            </MultiBinding>
          </Setter.Value>
        </Setter>
      </Style>
    </ResourceDicionary>
  </Window.Resource>
</Window>

界面

<TextBox x:Name="text1"/>
<TextBox x:Name = "text2"/>
<TextBlock Text="字符长度大于10" Style = "{StaticResource MultiBindingStyle}"/>

 

posted @ 2019-01-23 16:21  snake1118  阅读(3330)  评论(0编辑  收藏  举报