在理想情况下,我们可以将ComboBoxItem 上的IsHighlighted 属性绑定到我们ViewModel 中的一个属性,并将Mode 设置为OneWayToSource:
<ComboBoxItem IsHighlighted="{Binding MyViewModelBoolProperty}" />
但是,WPF不允许允许在只读依赖属性上设置任何绑定,即使模式是 OneWayToSource(这表明我们的意图是永远不会更新依赖属性,只有指定的来源)。为此存在一个连接问题:
http://connect.microsoft.com/VisualStudio/feedback/details/540833/onewaytosource-binding-from-a-readonly-dependency-property
在连接问题中,有一个建议的解决方法可能对您有用。采用的方法是创建一个MultiBinding 到Tag,其中一个绑定到您的只读属性,另一个绑定到您的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 并混淆了我们的真实意图,但它是有效的。希望这会有所帮助!