IValueConverter类 Bingding.Converter
https://www.cnblogs.com/gaoshang212/p/4973300.html?utm_source=tuicool&utm_medium=referral
1.需求说明
显示界面上有多个RadioButton,需要选择其中一个来修改一个枚举类型的值。举例:有七个RadioButton,星期一到星期日,选择其中之一可以改变枚举类型week的对应值。
2.实现方法
利用Converter和ConevertParamter属性。
3.步骤
1.新加一个类继承自IValueConverter。
class RadioBtConvter : IValueConverter
{
public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
{
return value == null ? false : value.Equals(parameter);
}
public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
{
return value != null && value.Equals(true) ? parameter : Binding.DoNothing;
}
}
程序逻辑:Convert(把ConverterParameter转化成Ischeck能用的bool量),如果要使用的转换器参数 == 绑定源的值,返回true;否则返回false;ConvertBack(把Ischeck的bool量转化成枚举类型的week),如果Ischeck的值是true,那么返回枚举,否则执行Binding.DoNothing。(用作返回值以指示绑定引擎不执行任何操作。)
2.把IValueConverter类添加到App.xaml的资源字典中
xmlns:convter="clr-namespace:comboxTest.Untils"
<Application.Resources>
<convter:RadioBtConvter x:Key="RadioBtConvter"/>
</Application.Resources>
3.xaml文件中把RadioButton进行Binding
<RadioButton Content="星期一" Margin="5",IsChecked="{Binding week, Mode=TwoWay,Converter={StaticResource RadioBtConvter},ConverterParameter={x:Static local:WeekEnum.Monday}}"/>
<TextBox Margin="5" Width="70" Text="{Binding today}"/>
4.
private WeekEnum _week;
public WeekEnum week
{
get { return _week; }
set
{
_week = value;
switch(this._week)
{
case WeekEnum.Monday:
this.today = "Monday";
break;
case WeekEnum.Tuesday:
this.today = "Tuesday";
break;
case WeekEnum.Wednesday:
this.today = "Wednesday";
break;
case WeekEnum.Thursday:
this.today = "Thursday";
break;
case WeekEnum.Friday:
this.today = "Friday";
break;
case WeekEnum.Saturday:
this.today = "Saturday";
break;
case WeekEnum.Sunday:
this.today = "Sunday";
break;
}
this.RaisePropertyChanged("week");
}
}
}