【问题标题】:Multiple binding in WPF for boolean converterWPF中用于布尔转换器的多重绑定
【发布时间】:2017-06-16 13:00:11
【问题描述】:

我正在开发一个需要检查一些可用性属性的小型应用程序。我正在使用用户界面 WPF。如果从组合框中进行选择,我需要更改一些前景色。我有这个数据模板:

<DataTemplate x:Key="userTemplate">
<TextBlock VerticalAlignment="Center">
    <Image Source="imgsource.png" Height="25" Width="25" />
    <Run Text="{Binding BooleanObjectName}" Foreground="{Binding boolobject, Converter={StaticResource convAvailability}}"/>
</TextBlock>

所以我使用 IValueConverter 来进行这种转换,它将颜色设置为前景:

public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
{
    BooleanObject boolobject = (BooleanObject)value;
    if (boolobject.IsBoolValueOne) return System.Drawing.Brushes.Green;
    else if (boolobject.IsBoolValueTwo) return System.Drawing.Brushes.Red;
    else if (boolobject.IsBoolValueThree) return (SolidColorBrush)(new BrushConverter().ConvertFrom("#d3d300"));
    else return System.Drawing.Brushes.Black;
}

这有什么问题,因为在我的界面中我总是得到黑色。对此有什么想法吗?

任何帮助将不胜感激。 提前致谢。

【问题讨论】:

  • 您需要 WPF 项目中 System.Windows.Media 命名空间中的 BrushSystem.Drawing 命名空间用于 WinForms。
  • 你的 Convert 方法被调用了吗?
  • @mm8 我试过调试,我认为它没有被调用
  • @mm8 DataTemplate 在窗口外的 ResourceDictionary 上定义
  • 如果你绑定错误,它通常会将错误写入输出窗口而不破坏代码,检查那里是否有任何错误消息

标签: c# wpf combobox binding


【解决方案1】:

正如@Funk 所指出的,您返回的画笔类型错误。你应该返回一个System.Windows.Media.Brush 对象:

public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
{
    BooleanObject boolobject = (BooleanObject)value;
    if (boolobject.IsBoolValueOne)
        return System.Windows.Media.Brushes.Green;
    else if (boolobject.IsBoolValueTwo)
        return System.Windows.Media.Brushes.Red;
    else if (boolobject.IsBoolValueThree)
        return (SolidColorBrush)(new BrushConverter().ConvertFrom("#d3d300"));

    return System.Windows.Media.Brushes.Black;
}

如果您对boolobject 属性的绑定确实有效,那么它应该可以工作。否则你的转换器根本不会被调用。

如果你想绑定到对象本身,你应该指定一个'.'的路径:

<TextBlock VerticalAlignment="Center">
    <Image Source="imgsource.png" Height="25" Width="25" />
    <Run Text="{Binding BooleanObjectName}" Foreground="{Binding Path=., Converter={StaticResource convAvailability}}"/>
</TextBlock>

【讨论】:

  • 没关系。解决了这个问题,因为我的代码没有正确设置 ComboBoxitem.IsSelected 值。
  • “已选择绿色组合框项目”。没有其他人,但您应该知道这意味着什么。您是否在 Convert 方法中设置了断点? IsBoolValueOne、IsBoolValueTwo 和 IsBoolValueThree 属性返回什么?可能是假的。
  • 非常感谢您的帮助!
猜你喜欢
  • 1970-01-01
  • 2015-01-20
  • 2011-03-13
  • 1970-01-01
  • 2013-08-18
  • 2017-08-15
  • 2010-12-30
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多