我想在选择组合框时启用文本框。注意组合框项目没有定义,而是我在combox中使用了项目源来获取组合框项目的列表。我想在选择combox项目时更改文本框的属性。
(评论贴在原始问题上)
<DataTrigger Binding="{Binding ElementName=cmbInstrumentType,
Path=SelectedIndex}"
Value="1" >
<Setter Property="IsEnabled" Value="true" />
<Setter Property="Background" Value="White" />
</DataTrigger>
我想在XAML中只在后面的代码中使用它。我不想为每个索引值重复一遍 -
答案 0 :(得分:7)
虽然更好的方法是使用MVVM模式并绑定到ViewModel中的属性(如Dabblenl建议的那样),但我认为你可以达到你想要的效果:
<StackPanel>
<ComboBox ItemsSource="{Binding Items}" Name="cmbInstrumentType"/>
<TextBox>
<TextBox.Style>
<Style TargetType="TextBox">
<Style.Triggers>
<DataTrigger Binding="{Binding ElementName=cmbInstrumentType, Path=SelectedItem}" Value="{x:Null}">
<Setter Property="IsEnabled" Value="False"/>
</DataTrigger>
</Style.Triggers>
</Style>
</TextBox.Style>
</TextBox>
</StackPanel>
如果在组合框中没有选择任何项目,这将禁用文本框。
修改:扩展的代码段
答案 1 :(得分:2)
我认为执行此类操作的最佳方法是使用转换器,因此您不必使用处理该问题的样式污染View并且逻辑不在视图中
类似这样的事情
IsEnabled="{Binding ElementName=cboVersion, Path=SelectedItem, Converter={StaticResource ObjectToBoolConverter}}"
当然你需要ObjectToBool转换器,类似这样(非常简单,没有类型检查等等......应该进行改进)
public class ObjectToBoolConverter : IValueConverter {
public object Convert(object value, Type targetType, object parameter, CultureInfo culture) {
return value != null;
}
public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture) {
throw new NotImplementedException();
}
}
并记得在resourcedictionary中注册转换器 e.g。
<Converters:ObjectToBoolConverter x:Key="ObjectToBoolConverter"/>