WPF中的ComboBoxItems的数据绑定是突出显示的

时间:2011-10-09 20:04:17

标签: c# wpf data-binding mvvm combobox

我想将ComboBoxItem.IsHighlighted属性放入我的ViewModel中。我想我可以设置项容器样式并根据该属性执行触发器,但后来我卡住了。

<ComboBox ItemsSource="{Binding StartChapters}" SelectedItem="{Binding SelectedStartChapter}">
    <ComboBox.ItemContainerStyle>
        <Style TargetType="ComboBoxItem">
            <Style.Triggers>
                <Trigger Property="IsHighlighted" Value="True">
                    <Setter ??? />
                </Trigger>
            </Style.Triggers>
        </Style>
    </ComboBox.ItemContainerStyle>
</ComboBox>

我能找到的所有示例都是设置其他UI属性,而不是将数据提供给datacontext。

任何人都知道如何实现这一目标?

1 个答案:

答案 0 :(得分:1)

在一个完美的世界中,我们可以将IsHighlighted上的ComboBoxItem属性绑定到ViewModel中的属性,并将Mode设置为OneWayToSource

<ComboBoxItem IsHighlighted="{Binding MyViewModelBoolProperty}" />

但是,WPF确实允许在只读依赖项属性上设置任何绑定,即使模式为OneWayToSource(表明我们的意图永远不会更新依赖项属性,仅它的指定来源)。有一个连接问题:

http://connect.microsoft.com/VisualStudio/feedback/details/540833/onewaytosource-binding-from-a-readonly-dependency-property

在连接问题中,建议的解决方法可能对您有用。所采用的方法是创建MultiBindingTag,其中一个绑定到您的只读属性,另一个绑定到您的ViewModel。然后提供一个转换器来设置您的ViewModel属性:

   <Grid>
        <Grid.Resources>
            <l:MyConverter x:Key="MyConverter" />
        </Grid.Resources>

        <ComboBox VerticalAlignment="Center">
            <ComboBoxItem Content="Content Placeholder One" />
            <ComboBoxItem Content="Content Placeholder Two" />
            <ComboBoxItem Content="Content Placeholder Three" />
            <ComboBox.ItemContainerStyle>
                <Style TargetType="{x:Type ComboBoxItem}">
                    <Setter Property="Tag">
                        <Setter.Value>
                            <MultiBinding Converter="{StaticResource MyConverter}">
                                <Binding RelativeSource="{RelativeSource Self}" Path="IsHighlighted" />
                                <Binding />
                            </MultiBinding>
                        </Setter.Value>
                    </Setter>
                </Style>
            </ComboBox.ItemContainerStyle>
        </ComboBox>
    </Grid>

和转换器:

public class MyConverter : IMultiValueConverter
    {
        public object Convert(object[] values, Type targetType, object parameter, System.Globalization.CultureInfo culture)
        {
            if (values != null && values[0] is bool && values[1] is MyViewModel)
            {
                ((MyViewModel)values[1]).MyBoolProperty = (bool)values[0];
                return (bool)values[0];
            }

            return DependencyProperty.UnsetValue;
        }

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

不是最好的解决方案,因为它涉及Tag并模糊了我们的真实意图,但它是有效的。希望这有帮助!