您好,登录后才能下订单哦!
WPF中经常会需要用到多个Radiobutton选择项,并且需要将选中的选项映射到某个枚举值enum中。
这种情形的解决办法如下:
1) 需要创建一个UserControl,举个例子代码如下:
<UserControl x:Class="ShangfeiXApp.XModeUserControl"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:src="clr-namespace:ShangfeiXApp"
mc:Ignorable="d">
<UserControl.Resources>
<src:XDataModeValueConverter x:Key="XmodeConverter"/>
</UserControl.Resources>
<Grid x:Name="LayoutRoot" Background="White" Margin="10">
<Grid.RowDefinitions>
<RowDefinition Height="Auto"/>
<RowDefinition Height="Auto"/>
<RowDefinition Height="Auto"/>
</Grid.RowDefinitions>
<StackPanel Orientation="Horizontal" Grid.Row="1" HorizontalAlignment="Center">
<RadioButton Content="Background" Margin="0 0 10 0" GroupName="Mode" IsChecked="{Binding mode, Mode=TwoWay, ConverterParameter=BACKGROUND_MODE, Converter={StaticResource XmodeConverter}}" />
<RadioButton Content="Full scale" Margin="0 0 10 0" GroupName="Mode" IsChecked="{Binding mode, Mode=TwoWay, ConverterParameter=FULLSCALE_MODE, Converter={StaticResource XmodeConverter}}" />
<RadioButton Content="Normal" Margin="0 0 10 0" GroupName="Mode" IsChecked="{Binding mode, Mode=TwoWay, ConverterParameter=NORMAL_MODE, Converter={StaticResource XmodeConverter}}" />
</StackPanel>
</Grid>
</UserControl>
2)定义枚举和一个携带枚举属性的类,如下:
public enum XDataMode { BACKGROUND_MODE, FULLSCALE_MODE, NORMAL_MODE };
public class XDataModeValue : INotifyPropertyChanged
{
private XDataMode _mode = XDataMode.BACKGROUND_MODE;
public XDataMode mode
{
get { return _mode; }
set
{
if (_mode != value)
{
_mode = value;
NotifyPropertyChanged("mode");
}
}
}
private void NotifyPropertyChanged(string propertyName)
{
if (PropertyChanged != null)
{
PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
}
}
public event PropertyChangedEventHandler PropertyChanged;
}
3)定义bool与该枚举值得转化类:
[ValueConversion(typeof(XDataMode), typeof(Boolean))]
public class XDataModeValueConverter : IValueConverter
{
// bool转Visibility
public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
{
return (value.ToString() == parameter.ToString());
}
public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
{
return (bool)value ? Enum.Parse(targetType, parameter.ToString(), true) : null;
}
}
4)在mainwindows.cs中或其他代码中类似如下定义一个变量:
public XDataModeValue Xdatamodevalue { get; set; }
5)在MainWindow中实现如下源码,即给定上下文,便于绑定
public MainWindow()
{
InitializeComponent();
...
Loaded += MainPage_Loaded;
}
private void MainPage_Loaded(object sender, RoutedEventArgs e)
{
DataContext = Xdatamodevalue;
}
完毕!
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。