如何通过绑定设置带DataTemplate的ComboBox中ComboboxItem的IsEnable属性
解决方法
- 你当前代码的核心问题是:
ComboBoxItem是ComboBox的项容器,不属于DataTemplate内部的视觉树范围,所以定义在DataTemplate.Resources里的样式无法作用到ComboBoxItem上。 - 注意拼写区分:ComboBoxItem的自带禁用属性是
IsEnabled(末尾带d),你绑定的源属性是Users类自定义的IsEnable,绑定路径保持和你定义的类属性一致即可。
正确XAML代码
<ComboBox x:Name="ComboBoxUsers" ItemsSource="{Binding Users}" FontFamily="Arial" FontSize="11" Grid.Row="3" Height="30" Margin="10,5,5,5"> <!-- 通过ItemContainerStyle直接指定ComboBoxItem的样式 --> <ComboBox.ItemContainerStyle> <Style TargetType="ComboBoxItem"> <Setter Property="IsEnabled" Value="{Binding IsEnable}"/> </Style> </ComboBox.ItemContainerStyle> <ComboBox.ItemTemplate> <DataTemplate> <StackPanel Orientation="Horizontal" > <Image /> <TextBlock Text="{Binding Name}"/> <!-- 补充用户名绑定,否则下拉项不会显示用户名称 --> </StackPanel> </DataTemplate> </ComboBox.ItemTemplate> </ComboBox>
可选优化(运行时动态更新场景)
如果IsEnable属性会在运行时修改,需要让界面同步更新状态,给Users类实现INotifyPropertyChanged接口即可:
public class Users : INotifyPropertyChanged { private string _name; public string Name { get => _name; set { _name = value; OnPropertyChanged(); } } private bool _isEnable; public bool IsEnable { get => _isEnable; set { _isEnable = value; OnPropertyChanged(); } } public event PropertyChangedEventHandler PropertyChanged; protected virtual void OnPropertyChanged([CallerMemberName] string propertyName = null) { PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName)); } public Users() { } }
内容的提问来源于stack exchange,提问作者abdou31
相关产品推荐
相关产品推荐

