C# WPF中ComboBoxItems的数据绑定
我想将ComboBoxItem.IsHighlighted属性放入我的ViewModel中。我想我可以设置项目容器样式并基于该属性执行触发器,但后来我被卡住了C# WPF中ComboBoxItems的数据绑定,c#,wpf,data-binding,mvvm,combobox,C#,Wpf,Data Binding,Mvvm,Combobox,我想将ComboBoxItem.IsHighlighted属性放入我的ViewModel中。我想我可以设置项目容器样式并基于该属性执行触发器,但后来我被卡住了 <ComboBox ItemsSource="{Binding StartChapters}" SelectedItem="{Binding SelectedStartChapter}"> <ComboBox.ItemContainerStyle> <Style TargetType=
<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
有人知道这是如何实现的吗?在一个完美的世界中,我们可以将
ComboBoxItem
上的IsHighlighted
属性绑定到ViewModel中的一个属性,并将模式设置为OneWayToSource
:
<ComboBoxItem IsHighlighted="{Binding MyViewModelBoolProperty}" />
和转换器:
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();
}
这不是最好的解决方案,因为它涉及到标记
,混淆了我们的真正意图,但它是有效的。希望这有帮助 在一个完美的世界中,我们可以将ComboBoxItem
上的IsHighlighted
属性绑定到ViewModel中的属性,并将模式设置为OneWayToSource
:
<ComboBoxItem IsHighlighted="{Binding MyViewModelBoolProperty}" />
和转换器:
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();
}
这不是最好的解决方案,因为它涉及到标记
,混淆了我们的真正意图,但它是有效的。希望这有帮助