【发布时间】:2016-03-17 15:05:12
【问题描述】:
玩MultiBinding:
我想要什么:单击任一复选框应该切换所有其他复选框。
问题:点击A不会改变B,点击B不会改变A。 Result 有效。
问题:我将如何解决它,同时仍然使用MultiBinding?
P.S.:这是为了解决更复杂的problem,请在提供将所有复选框绑定到单个属性之前参考它。
下面是mcve。
xaml:
<StackPanel>
<CheckBox Content="A" IsChecked="{Binding A}" />
<CheckBox Content="B" IsChecked="{Binding B}" />
<CheckBox Content="Result">
<CheckBox.IsChecked>
<MultiBinding Converter="{local:MultiBindingConverter}">
<Binding Path="A" />
<Binding Path="B" />
</MultiBinding>
</CheckBox.IsChecked>
</CheckBox>
</StackPanel>
cs:
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
DataContext = new ViewModel();
}
}
视图模型:
public class ViewModel : INotifyPropertyChanged
{
public event PropertyChangedEventHandler PropertyChanged;
public void OnPropertyChanged([CallerMemberName] string property = "") => PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(property));
bool _a;
public bool A
{
get { return _a; }
set { _a = value; OnPropertyChanged(); }
}
bool _b;
public bool B
{
get { return _b; }
set { _b = value; OnPropertyChanged(); }
}
}
转换器:
public class MultiBindingConverter : MarkupExtension, IMultiValueConverter
{
public MultiBindingConverter() { }
public override object ProvideValue(IServiceProvider serviceProvider) => this;
object[] _old;
public object Convert(object[] values, Type targetType, object parameter, CultureInfo culture)
{
// first time init
if (_old == null)
_old = values.ToArray();
// find if any value is changed and return value
for (int i = 0; i < values.Length; i++)
if (values[i] != _old[i])
{
_old = values.ToArray();
return values[i];
}
// if no changes return first value
return values[0];
}
public object[] ConvertBack(object value, Type[] targetTypes, object parameter, CultureInfo culture) =>
Enumerable.Repeat(value, targetTypes.Length).ToArray();
}
【问题讨论】:
-
为什么不使用返回 || 的属性结果b 并在更新 a 或 b 时提高属性更改?
-
@Boo,因为您还没有阅读过
P.S.;)其中一个属性(例如A)在 ViewModel 中将不可用。 -
我的两分钱:你在这里错过了一个 ViewModel。
-
@ArnaudWeil,按
control+F,输入ViewModel,然后按Enter。 -
有趣。说真的,您所说的 ViewModel 不是 ViewModel,因为它不会为每个输入公开一个属性。您的多重绑定是为了隐藏它不是读取 ViewModel 的事实。
标签: c# wpf multibinding two-way-binding