您好,登錄后才能下訂單哦!
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進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。