[英]WPF Combobox Item Background Binding to Item Property
如何獲取要綁定到模型的布爾值屬性的組合框項的背景顏色?
在搜索和嘗試之后,我可以弄清楚這一點,但我不確定這是正確的方法。 好像比較啰嗦
*注意:在起草這個問題的過程中,我得出了以下解決方案
我有一個簡單的代碼示例,說明我正在使用的內容:
我有一個模型和視圖模型,如:
public class YesNoModel
{
public string Name { get; set; }
public bool Value { get; set; }
}
public class ViewModel
{
public IEnumerable<YesNoModel> YesNoItems { get; set; }
public ViewModel()
{
var list = new List<YesNoModel>();
list.Add(new YesNoModel() { Name = "Yes", Value = true });
list.Add(new YesNoModel() { Name = "No", Value = false });
YesNoItems = list;
}
}
將布爾值轉換為顏色的值轉換器
public class BoolToBackgroundGrayConverter : IValueConverter
{
public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
{
if ((bool)value)
{
return Brushes.LightGray;
}
else
{
return Brushes.Transparent;
}
}
public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
{
throw new NotImplementedException();
}
}
和 XAML 綁定到窗口中的組合框
<Window.Resources>
<local:BoolToBackgroundGrayConverter x:Key="BoolToBackgroundGrayConverter"/>
</Window.Resources>
<Window.DataContext>
<local:ViewModel />
</Window.DataContext>
<Grid>
<ComboBox ItemsSource="{Binding YesNoItems}">
<ComboBox.ItemTemplate>
<DataTemplate>
<TextBlock Text="{Binding Name}" Background="{Binding Value, Converter={StaticResource BoolToBackgroundGrayConverter}}" />
</DataTemplate>
</ComboBox.ItemTemplate>
</ComboBox>
</Grid>
這是正確的方法嗎? 這似乎相當冗長,而且在值轉換器中對顏色進行硬編碼也感覺有些錯誤
沒有綁定轉換器的替代方案可能是 DataTrigger:
<ComboBox.ItemTemplate>
<DataTemplate>
<TextBlock Text="{Binding Name}">
<TextBlock.Style>
<Style TargetType="TextBlock">
<Setter Property="Background" Value="Transparent"/>
<Style.Triggers>
<DataTrigger Binding="{Binding Value}" Value="True">
<Setter Property="Background" Value="LightGray"/>
</DataTrigger>
</Style.Triggers>
</Style>
</TextBlock.Style>
</TextBlock>
</DataTemplate>
</ComboBox.ItemTemplate>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.