3

几个小时以来一直在谷歌上搜索这个问题,但看不到我哪里出错了。

我有以下转换器,它也只返回 Brushes.Red(尝试过 Colors.Red),但仍然没有运气。

public class ColorConverter : IValueConverter
{
    private static ColorConverter instance = new ColorConverter();
    public static ColorConverter Instance
    {
        get
        {
            return instance;
        }
    }

    public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
    {
        return Brushes.Red;
    }
    public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
    {
        throw new Exception("The method or operation is not implemented.");
    }
}

现在在我的 xaml 中,我有以下代码:

<StackPanel Orientation="Vertical">
    <TextBlock Text="{Binding Value}" TextAlignment="Center" Foreground="{Binding Path=color, Converter={x:Static local:ColorConverter.Instance}}" Margin="2"/>
</StackPanel>

我在顶部设置了以下命名空间:

xmlns:local="clr-namespace:Dashboard"

现在我有以下绑定到堆栈面板的类:

public class MyClass : INotifyPropertyChanged
{
    public String Value;
    public Color color;

    // Declare the PropertyChanged event
    public event PropertyChangedEventHandler PropertyChanged;
    public void NotifyPropertyChanged(String info)
    {
        if (PropertyChanged != null)
        {
            PropertyChanged(this, new PropertyChangedEventArgs(info));
        }
    }
}

数据绑定(值)工作得非常好,但是转换器不想启动,我试图在转换器的 Convert 方法中设置一个断点,但是在调试时不会触发,看起来好像我的调试器没有被调用。

任何人都可以对此有所了解吗?

4

2 回答 2

2

我很惊讶您说绑定本身有效,因为“值”和“颜色”是字段,并且绑定到字段不应该起作用。

于 2010-02-11T14:02:55.737 回答
1

好吧,这就是我在项目中的做法。我修改了我的代码以反映您正在尝试做的事情。我希望它有所帮助。我无法回答为什么您的单例方法不起作用。

班级:

public class ColorConverter : IValueConverter
{
    public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
    {
        return Brushes.Red;
    }
    public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
    {
        throw new Exception("The method or operation is not implemented.");
    }
}

在我的 UserControl.Resources 元素中:

<UserControl.Resources>
    <local:ColorConverter x:Key="MyColorConverter" />
</UserControl.Resources>

StackPanel 元素:

<StackPanel Orientation="Vertical">
    <TextBlock Text="{Binding Value}" TextAlignment="Center" Foreground="{Binding Path=color, Converter={StaticResource MyColorConverter}}" Margin="2"/>
</StackPanel>

另外,您是否检查了“输出”窗口以查看是否有任何错误?您还应该阅读Bea Stollnitz 关于调试数据绑定的文章。实际上,她有一个关于 IValueConverters 的特定部分,有一天可能会派上用场。

于 2010-02-11T14:01:05.200 回答