使用MVVM样式我已成功将ObservableCollection<string>
绑定到ListBox
,将值显示为RadioButton
s。控件的行为完全符合预期。
现在我遇到了与此TextBox
绑定的ListBox
个问题:我希望只要SelectedItem
中的ListBox
等于特定值(例如{ {1}})要启用ValueForEnabled
es,否则应禁用它们。
我知道我必须绑定到TextBox
SeletedItem
(名为ListBox
),但这究竟是如何完成的?
我想要这样的东西(伪代码):
lbSource
答案 0 :(得分:6)
OK! 解决了它(换句话说)我自己!对于任何想要了解的人:
<TextBox
...
usual property definitions
...
>
<TextBox.Style>
<Style>
<Setter Property="TextBox.IsEnabled" Value="False"/>
<Style.Triggers>
<DataTrigger Binding="{Binding ElementName=lbSource , Path=SelectedItem}" Value="ValueForEnabled">
<Setter Property="TextBox.IsEnabled" Value="true"/>
</DataTrigger>
</Style.Triggers>
</Style>
</TextBox.Style>
</TextBox>
答案 1 :(得分:3)
我个人认为,如果您使用的是MVVM,那么您应该将代码保留在ViewModel中。所以如果您的VM是这样的:
public class MyViewModel
{
public ObservableCollection<string> myColl {get;set;}
public string SelectedString {get;set;}
public bool IsEnabled
{
get { return SelectedString == "Desired string value";}
}
}
然后,您只需将文本框IsEnabled属性绑定到ViewModel上的IsEnabled属性
我说这个的原因是你的要求可能会改变何时启用文本框,如果你这样做,你不必触摸你的视图(代码/逻辑不应该驻留)
所以现在你在视图中这样做了,就是这样
<TextBox IsEnabled={Binding IsEnabled} Text={Binding SelectedString}/>
希望我理解你的问题,这有助于
答案 2 :(得分:2)
将这只猫皮肤化的一种方法是将字符串(在列表框中)转换为bool以传递给IsEnabledProperty ......
首先,创建一个实现IValueConverter接口的类,如:
public class StringToBoolConverter : IValueConverter
{
#region IValueConverter Members
public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
if (value == null)
return false;
string keyword = value.ToString();
if (keyword.Equals(parameter.ToString(), StringComparison.CurrentCultureIgnoreCase))
return true;
return false;
}
public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
throw new NotImplementedException();
}
#endregion
}
请注意您不需要实现ConvertBack方法?那是因为你只需要将字符串变为bools,而不是反之亦然......
因此,您可以在xaml中声明转换器的实例,例如
<Window
...
xmlns:local="clr-namespace:WpfApplication1">
<Window.Resources>
<local:StringToBoolConverter x:Key="stringToBoolConverter" />
</Window.Resources>
最后,您可以将TextBox绑定到ListBox的SelectedValue,例如:
<TextBox Grid.Row="0" Width="90" Height="30"
IsEnabled="{Binding ElementName=lbSource, Path=SelectedValue, Converter={StaticResource stringToBoolConverter}, ConverterParameter=ValueForEnabled}">
</TextBox>
注意:这仅在ListBox包含字符串时才有效,并且您可以确定SelectedValue属性是字符串...