为什么绑定“自我”不起作用?

时间:2013-03-07 10:52:13

标签: wpf xaml binding relativesource

我尝试将控件的Tag属性绑定到控件的Visibility属性,但是我在VS中收到以下错误:

  

对象引用未设置为对象的实例

XAML如下:

<RadioButton GroupName="NavButtonSide" 
             Tag="7"  
             Visibility="{Binding Path=Tag, 
                                  Converter={StaticResource ControlTagVisibilityConverter}, 
                                  RelativeSource={RelativeSource Mode=Self}}"/>

谁能告诉我如何解决它?

1 个答案:

答案 0 :(得分:4)

绑定没有错。这对我来说很好;

<Window.Resources>
    <local:ControlTagVisibilityConverter x:Key="ControlTagVisibilityConverter" /> 
</Window.Resources>

<RadioButton 
    Tag="7" 
    Visibility="{Binding Path=Tag, 
        Converter={StaticResource ControlTagVisibilityConverter}, 
        RelativeSource={RelativeSource Mode=Self}}"/>

ControlTagVisibilityConverter.cs

public class ControlTagVisibilityConverter : IValueConverter
{
    public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
    {
        var valueAsString = (string) value;
        var valueAsInt = int.Parse(valueAsString);

        switch (valueAsInt)
        {
            case 7:
                return Visibility.Visible;
            default:
                return Visibility.Hidden;
        }
    }

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