można utworzyć enum
zawierający Wartości RadioButton
obiektów jak nazwy (w przybliżeniu), a następnie wiążą właściwość IsChecked
do właściwości typu tego enum
stosując EnumToBoolConverter
.
public enum Options
{
All, Current, Range
}
Następnie w modelu widoku lub kodu tyle:
private Options options = Options.All; // set your default value here
public Options Options
{
get { return options; }
set { options = value; NotifyPropertyChanged("Options"); }
}
Dodaj Converter
:
[ValueConversion(typeof(Enum), typeof(bool))]
public class EnumToBoolConverter : IValueConverter
{
public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
{
if (value == null || parameter == null) return false;
string enumValue = value.ToString();
string targetValue = parameter.ToString();
bool outputValue = enumValue.Equals(targetValue, StringComparison.InvariantCultureIgnoreCase);
return outputValue;
}
public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
{
if (value == null || parameter == null) return null;
bool useValue = (bool)value;
string targetValue = parameter.ToString();
if (useValue) return Enum.Parse(targetType, targetValue);
return null;
}
}
Wtedy wreszcie dodać powiązań w interfejsie użytkownika, ustawiając odpowiednią ConverterParameter
:
<RadioButton Content="All Pages" IsChecked="{Binding Options, Converter={
StaticResource EnumToBoolConverter}, ConverterParameter=All}" />
<RadioButton Content="Current Page" IsChecked="{Binding Options, Converter={
StaticResource EnumToBoolConverter}, ConverterParameter=Current}" />
<RadioButton Content="Page Range" IsChecked="{Binding Options, Converter={
StaticResource EnumToBoolConverter}, ConverterParameter=Range}" />
Teraz możesz stwierdzić, które ustawienie jest ustawione, patrząc na zmienną Options
w modelu widoku lub kodu z tyłu. Będziesz także mógł ustawić sprawdzane RadioButton
, ustawiając właściwość Options
.
Hi @nit: Jest to bardzo proste, szybkie, eleganckie i rzeczywiście warte rozwiązania. Dzięki za odpowiedź. :) – Bhramar
@Bhramar cieszę się, że zadziałało dla ciebie :) – Nitin
Buddy, Rozwiązanie działa dobrze, ALE jak ustawić domyślne sprawdzone do któregokolwiek z mojego RadioButton. Możemy ustawić go w contructor, ale to naruszy zasady MVVM. Wszelkie pomysły byłyby pomocne. – Bhramar