【问题标题】:Highlight Combobox when SelectedValue is not in ItemsSource当 SelectedValue 不在 ItemsSource 中时突出显示 Combobox
【发布时间】:2018-10-18 11:07:45
【问题描述】:

我有一个包含许多组合框的窗口。这些Comboboxes长这样,有一种风格:

<ComboBox Style="{StaticResource ComboBoxFlat}" 
              ItemsSource="{Binding Source={x:Static binding:BindingCollections.Names}}" 
              SelectedValuePath="Key"
              DisplayMemberPath="Value"
              SelectedValue="{Binding NameID}"/>

ItemsSource 是一个键值列表,显示值。到目前为止,这一切都有效。

现在可能发生绑定到 SelectedValue 的属性包含 ItemsSource 中不存在的键。如果发生这种情况,应该以某种方式标记组合框,例如组合框应该有一个红框。

最好的方法是什么? 是否可以在 Combobox 样式中定义这样的行为?

【问题讨论】:

  • 这可以通过触发器实现,但可能无法在组合框中显示无效值。
  • @Sham 好的,我明白了!在 ComboBox 中不需要显示无效键,突出显示即可。

标签: c# wpf data-binding combobox


【解决方案1】:

如果SelectedIndex 属性返回-1NameID属性返回一个值,例如:

class MultiConverter : IMultiValueConverter
{
    public object Convert(object[] values, Type targetType, object parameter, CultureInfo culture)
    {
        return (int)values[0] == -1 && values[1] != null;
    }

    public object[] ConvertBack(object value, Type[] targetTypes, object parameter, CultureInfo culture)
    {
        throw new NotSupportedException();
    }
}

XAML:

<ComboBox ... 
          SelectedValue="{Binding NameID}">
    <ComboBox.Resources>
        <local:MultiConverter x:Key="MultiConverter" />
    </ComboBox.Resources>
    <ComboBox.Style>
        <Style TargetType="ComboBox" BasedOn="{StaticResource ComboBoxFlat}">
            <Style.Triggers>
                <DataTrigger Value="True">
                    <DataTrigger.Binding>
                        <MultiBinding Converter="{StaticResource MultiConverter}">
                            <Binding Path="SelectedIndex" RelativeSource="{RelativeSource Self}" />
                            <Binding Path="NameID" />
                        </MultiBinding>
                    </DataTrigger.Binding>
                    <Setter Property="BorderBrush" Value="Red" />
                    <Setter Property="BorderThickness" Value="10" />
                </DataTrigger>
            </Style.Triggers>
        </Style>
    </ComboBox.Style>
</ComboBox>

【讨论】:

  • 不指定属性 (NameID) expilzit 也可以吗?
  • 不,当然需要指定要绑定的属性。
猜你喜欢
  • 2019-09-11
  • 2015-10-06
  • 2017-03-07
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-10-03
相关资源
最近更新 更多