好的,这是一个新手问题,不幸的是我无法找到答案。
基本上,当对象的Disabled
属性设置为true时,将对象列表绑定到Combobox时,我希望Combobox项目的文本颜色设置为灰色。
这是我目前的代码:
Combobox项目数据类型
public class ListItem
{
public ListItem(string text)
{
Text = text;
}
public string Text { get; set; }
public bool Disabled { get; set; }
}
视图模型设置
public class MainPageViewModel : ReactiveObject
{
// In ReactiveUI, this is the syntax to declare a read-write property
// that will notify Observers, as well as WPF, that a property has
// changed. If we declared this as a normal property, we couldn't tell
// when it has changed!
private ListItem _selectedItem;
public ListItem SelectedItem
{
get => _selectedItem;
set => this.RaiseAndSetIfChanged(ref _selectedItem, value);
}
public List<ListItem> Items { get; set; }
public MainPageViewModel()
{
Items = new List<ListItem>
{
new ListItem ("A Cat"),
new ListItem ("A Dog"),
new ListItem ("A Mouse"),
new ListItem ("A Frog") { Disabled = true }
};
}
}
ReactiveUI绑定
public MainPage()
{
InitializeComponent();
ViewModel = new MainPageViewModel();
this.WhenActivated(d =>
{
this.OneWayBind(ViewModel, vm => vm.Items, v => v.MyComboBox.ItemsSource)
.DisposeWith(d);
this.Bind(ViewModel, vm => vm.SelectedItem, v => v.MyComboBox.SelectedItem)
.DisposeWith(d);
});
}
Xaml标记语言
<ComboBox
Name="MyComboBox"
Margin="0,0,0,20"
Foreground="black">
<ComboBox.ItemTemplate>
<DataTemplate>
<TextBlock Text="{Binding}" />
</DataTemplate>
</ComboBox.ItemTemplate>
<ComboBox.ItemContainerStyle>
<Style TargetType="ComboBoxItem">
<Style.Triggers>
<DataTrigger Binding="{Binding Path=Disabled}" Value="True">
<Setter Property="Foreground" Value="Gray" />
</DataTrigger>
</Style.Triggers>
</Style>
</ComboBox.ItemContainerStyle>
</ComboBox>
任何帮助都是欢迎的,请让我知道如果您需要更多信息。
解决方案:看起来在未来我需要在发布示例代码之前测试一下 - 我们实际的代码将 Disabled
属性设置为 readonly
,这可能会影响 WPF 绑定。将它改为公共的 set 和 get 就解决了第一个问题,看不到变灰!似乎长时间盯着一个问题会使你失明,而问题实际上是如此简单。
至于使选定的项目变灰,我将尝试一下并查看结果。
Disabled
属性吗?据我所知,您没有实现INotifyPropertyChanged
接口来通知任何更改。此外,您说当Disabled
为true
时要将颜色更改为Gray
,但在您的 XAML 中,它触发的是False
。如果您创建一个项并将其Disabled
属性最初设置为触发器值,那么它是否有效? - thatguyList<ListItem>
,其中一些项将设置Disabled
属性为true
。至于第二部分,那是一个打字错误,我在尝试让它工作 - 你是对的,它应该是Value="True"
,我会更新代码。 - ree6