我有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