WPF可见性绑定到转换的实例属性

时间:2013-06-28 20:04:22

标签: c# wpf binding type-conversion

所以我有一个按钮。我想根据类的整数属性的值设置按钮的可见性。这需要数据绑定和转换器。

按钮的XAML代码如下:

<Window.Resources>
        <local:Button1VisibilityConverter x:Key="Button1VisibilityConverter"/>
        <local:ModeValues x:Key="ModeHolder"/>
    </Window.Resources>
    <Grid>
        <StackPanel HorizontalAlignment="Left" Height="150" Margin="92,90,0,0" VerticalAlignment="Top" Width="301">
            <Button Content="1" Height="58" Background="#FFA20000" Foreground="White" Visibility="{Binding Source={StaticResource ModeHolder}, Path=State, Converter=Button1VisibilityConverter}"/>
            <Button Content="2" Height="58" Background="#FF16A200" Foreground="White"/>
            <Button Content="3" Height="58" Background="#FF4200A2" Foreground="White"/>
        </StackPanel>
    </Grid>

我的转换器如下:

class Button1VisibilityConverter : IValueConverter
    {
        public object Convert(object value, Type targettype, object parameter, System.Globalization.CultureInfo culture)
        {
            int mode = (int)value;
            if (mode == ModeValues.Red)
                return System.Windows.Visibility.Visible;
            else
                return System.Windows.Visibility.Collapsed;
        }

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

具有我想要控制可见性的属性的类如下:

public class ModeValues : IObservable<int>
    {
        private int _state = -1;

        public static int Red
        {
            get
            {
                return 0;
            }
        }

        public static int Green
        {
            get
            {
                return 1;
            }
        }

        public static int Purple
        {
            get
            {
                return 2;
            }
        }

        public int State
        {
            get
            {
                return this._state;
            }
            set
            {
                this.State = value;
            }
        }
    }

我不知道它为什么不起作用。我认为我必须将可见性绑定到ModeHolder实例的属性,使ModeHolder可观察,并将int转换为可见性。我错过了什么?

1 个答案:

答案 0 :(得分:0)

Converter=Button1VisibilityConverter

应该是:

Converter={StaticResource Button1VisibilityConverter}