我有ItemsControls与从CollectionViewSource绑定的项目。在ItemControl中绑定RadioButton的IsChecked属性
而且outsite另一个控制:
<TextBox Text="{Binding Path=SelectedCountryCode" />
每当我改变我想对应的RibbonRadioButton属性设置器isChecked为true或false TextBox的价值是什么,我试图完成的。
我有ItemsControls与从CollectionViewSource绑定的项目。在ItemControl中绑定RadioButton的IsChecked属性
而且outsite另一个控制:
<TextBox Text="{Binding Path=SelectedCountryCode" />
每当我改变我想对应的RibbonRadioButton属性设置器isChecked为true或false TextBox的价值是什么,我试图完成的。
你需要做的是创建一个ViewModel
有两个属性。
class MyViewModel
{
// Bind this to TextBox
public String SelectedCountryCode { get; set; }
// Bind this to ItemsControl
public ObservableCollection<Object> VisibleFlagsImageSourcePath { get; set; }
}
// Note I have omitted implementation of `INotifyPropertyChanged`. But, you will need to implement it.
和监控SelectedCountryCode
,每当它的变化,在VisibleFlagsImageSourcePath
收集改变适当的值。
好吧,假设SelectedCountryCode设置为“EN”。我怎样才能找到适当的RibbonRadioButton对应于ImageSource“flag_english”,并使其IsChecked? – brooNo 2011-01-27 15:03:36
单选按钮表示枚举值。这种情况下的文本框将代表一个开放值。您似乎需要的是一组开放值以及预设的枚举值选择。最能代表这一点的控件是一个组合框。
如果您决定继续使用单选按钮/文本框的方法,您可以调整人们用来将单选按钮绑定到枚举值的方法,但使用字符串字段/字符串字段类型转换器而不是枚举字段/枚举字段类型转换器。
看到这个答案对于如何绑定到枚举:How to bind RadioButtons to an enum?
为了适应这串,简单地创建一个名为KnownStringToBooleanConverter
类(注意,这是相同的实施EnumToBooleanConverter
):
public class KnownStringToBooleanConverter : IValueConverter
{
public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
return value.Equals(parameter);
}
public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
return value.Equals(true) ? parameter : Binding.DoNothing;
}
}
另外创建一个带有已知字符串的类型(类似于您将如何创建枚举):
public static class KnownCountryCodes
{
// Note: I'm guessing at these codes...
public const string England = "EN";
public const string Japan = "JP";
}
然后绑定到这个以类似的方式:
<RadioButton IsChecked="{Binding Path=SelectedCountryCode, Converter={StaticResource KnownStringToBooleanConverter}, ConverterParameter={x:Static local:KnownCountryCodes.England}}" />
<RadioButton IsChecked="{Binding Path=SelectedCountryCode, Converter={StaticResource KnownStringToBooleanConverter}, ConverterParameter={x:Static local:KnownCountryCodes.Japan}}" />
如果你想跨填充您的所有控件,那么您需要在您的视图模型来实现INotifyPropertyChanged
:
public class MyViewModel : INotifyPropertyChanged
{
// Bind this to TextBox and radio buttons. Populate the radio buttons manually
public string SelectedCountryCode
{
get
{
return selectedCountryCode;
}
set
{
selectedCountryCode = value;
RaiseNotifyPropertyChanged("SelectedCountryCode");
}
}
/* Todo: Implement NotifyPropertyChanged and RaiseNotifyPropertyChanged here */
private string selectedCountryCode;
}
当自定义值(不在列表中)时,单选按钮将全部变暗。当您输入列表中的值时,相应的单选按钮将亮起。当您选择一个正确的单选按钮时,该值将在文本框中更改。
这个View/ViewModel的东西叫做MVVM。 请参阅:http://msdn.microsoft.com/en-us/magazine/dd419663.aspx
为什么要单独控制一个单选按钮和文本框?你被允许有没有出现在单选按钮列表中的值? – 2011-05-04 22:25:36