如何将数据绑定到控件的Visibility属性

时间:2013-09-27 19:44:57

标签: c# wpf data-binding visibility

我知道控件的Visibility属性不能像其他属性一样绑定到数据。它需要某种转换器(?)。在尝试从this question实现解决方案时,我遇到了一个编译器错误:The resource "BoolToVisible" could not be resolved。我猜我必须创建一个名为ResourceKey的{​​{1}},我只是不知道如何。

我要求有人告诉我绑定到控件的Visibility属性的正确方法。

*我添加的控件是一个单选按钮。 *我的数据模型中BoolToVisible的{​​{1}}属性将绑定到此单选按钮。

数据模型属性:

bool

XAML:

isVisible

谢谢。

2 个答案:

答案 0 :(得分:4)

2个例子:

第一个使用转换器,如问题中所述:

  public class BooleanToVisibilityConverter : IValueConverter 
  {
     public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
     {            
         if (value == null || !(value is bool)) 
             return Binding.DoNothing;

         return (bool)value ? Visibility.Visible : Visibility.Collapsed; 
     }

     public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
     {
         return value;
     }
 }
xaml中的

<Window x:Class="Stackoverflow.MainWindow"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    Title="MainWindow" Height="350" Width="525"
    xmlns:local="clr-namespace:Stackoverflow"
    >
<Window.Resources>
    <local:BooleanToVisibilityConverter x:Key="booleanToVisibiltyConverter"/>
</Window.Resources>

<Grid>
    <Button Visibility="{Binding IsSomeThing,Converter={StaticResource booleanToVisibiltyConverter}}"/>        
</Grid>

第二个:

在您的DataContext中,您可以保持一个可见性属性

cs:

    private Visibility _myControlVisibility;
    public Visibility MyControlVisibility
    {
        get { return _myControlVisibility; }
        set { _myControlVisibility = value; }
    }

xaml:

    <Button Visibility="{Binding MyControlVisibility}"/>        

答案 1 :(得分:0)

您可以使用属性绑定可见性,只需要具有“可见性”的“依赖关系属性”字段:

    Public Property MyVisibility As Windows.Visibility
    Get
        Return GetValue(MyVisibilityProperty)
    End Get

    Set(ByVal value As Windows.Visibility)
        SetValue(MyVisibilityProperty, value)
    End Set
End Property

Public Shared ReadOnly MyVisibilityProperty As DependencyProperty = _
                       DependencyProperty.Register("MyVisibility", _
                       GetType(Windows.Visibility), GetType(MyWindow), _
                       New PropertyMetadata(Nothing))

然后像往常一样进行绑定(代码在VB中)。

请记住,在New PropertyMetadata中,您可以为对象设置初始状态,例如:

 Public Shared ReadOnly MyVisibilityProperty As DependencyProperty = _
                       DependencyProperty.Register("MyVisibility", _
                       GetType(Windows.Visibility), GetType(MyWindow), _
                       New PropertyMetadata(Windows.Visibility.Hidden))