我想将多个 CheckBox 项(IsChecked 属性)绑定(bind)到我的 ViewModel 中的单个属性。
ViewModel 属性称为 SelectedWeekdays (int),是所有选定工作日的总和。这个想法是工作日值的每一种可能组合都将始终产生唯一的总和。工作日在枚举中定义如下:
public enum Weekdays
{
Monday = 1
Tuesday = 2
Wednesday = 4
Thursday = 8
Friday = 16
Saturday = 32
Sunday = 64
}
例如,如果在 View 上选择了星期二和星期四,这应该导致 ViewModel 属性值为 10。
同样,如果 ViewModel 属性更改为 3,则应选中星期一和星期二的复选框。
我查看了 MultiBindings,但似乎我只能使用它来将单个 CheckBox 绑定(bind)到多个值。你能给我指出正确的方向吗?
这对你有用吗?我没有实现 ConvertBack
。这应该很容易。
public partial class MainWindow : Window, INotifyPropertyChanged
{
public MainWindow()
{
InitializeComponent();
this.DataContext = this;
SelectedWeekday = Weekdays.Tuesday;
}
private Weekdays _selectedWeekday;
public Weekdays SelectedWeekday
{
get { return _selectedWeekday; }
set
{
_selectedWeekday = value;
if(PropertyChanged != null)
PropertyChanged(this, new PropertyChangedEventArgs("SelectedWeekday"));
}
}
public event PropertyChangedEventHandler PropertyChanged;
}
[Flags]
public enum Weekdays
{
Monday = 1,
Tuesday = 2,
Wednesday = 4,
Thursday = 8,
Friday = 16,
Saturday = 32,
Sunday = 64
}
public class WeekdayConverter : IValueConverter, INotifyPropertyChanged
{
public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
var day = (Weekdays)value;
if ((day & Weekday) != 0)
return true;
return false;
}
public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
//Implement convertback
throw new NotImplementedException();
}
private Weekdays _weekday;
public Weekdays Weekday
{
get { return _weekday; }
set
{
_weekday = value;
if(PropertyChanged != null)
PropertyChanged(this, new PropertyChangedEventArgs("Weekday"));
}
}
public event PropertyChangedEventHandler PropertyChanged;
}
XAML:
<Window x:Class="WpfApplication2.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:view="clr-namespace:WpfApplication2"
Title="MainWindow" Height="350" Width="525">
<Window.Resources>
<view:WeekdayConverter x:Key="MondayConverter" Weekday="Monday"></view:WeekdayConverter>
<view:WeekdayConverter x:Key="TuesdayConverter" Weekday="Tuesday"></view:WeekdayConverter>
</Window.Resources>
<StackPanel>
<CheckBox Content="Monday" IsChecked="{Binding SelectedWeekday, Converter={StaticResource MondayConverter}}" />
<CheckBox Content="Tuesday" IsChecked="{Binding SelectedWeekday, Converter={StaticResource TuesdayConverter}}" />
</StackPanel>
</Window>
我是一名优秀的程序员,十分优秀!