【发布时间】:2016-03-31 05:47:07
【问题描述】:
假设我在 view.xaml 中有几个单选按钮:
<RadioButton GroupName="Group" Content="Item1" Command="{Binding ChangeRadioSelectionCommand}" CommandParameter="Item1" />
<RadioButton GroupName="Group" Content="Item2" Command="{Binding ChangeRadioSelectionCommand}" CommandParameter="Item2" />
<RadioButton GroupName="Group" Content="Item3" Command="{Binding ChangeRadioSelectionCommand}" CommandParameter="Item3" />
然后在我的viewmodel.cs 我有类似的东西:
public class ViewModel : BindableBase
{
private string radioSelection = "Item1";
public string RadioSelection
{
get { return this.radioSelection; }
set { SetProperty(ref this.radioSelection, value); }
}
public ViewModel()
{
this.ChangeRadioSelectionCommand = new DelegateCommand<string>(this.OnChangeRadioSelection, this.CanChangeRadioSelection);
}
public ICommand ChangeRadioSelectionCommand { get; private set; }
private void OnChangeRadioSelection(string radioSelection)
{
RadioSelection = radioSelection;
}
private bool CanChangeRadioSelection(string radioSelection) { return true; }
}
这对于将视图中的值获取到视图模型中效果很好,但是如果视图模型中的某些内容发生变化,我将如何从视图模型转到视图。为简单起见,假设我向 xaml 添加了一个按钮:
<Button Command="{Binding ResetRadioSelectionCommand}" />
它所做的只是将收音机选择重置为第一项,因此viewmodel.cs 看起来像:
public class ViewModel : BindableBase
{
private string radioSelection = "Item1";
public string RadioSelection
{
get { return this.radioSelection; }
set { SetProperty(ref this.radioSelection, value); }
}
public ViewModel()
{
this.ChangeRadioSelectionCommand = new DelegateCommand<string>(this.OnChangeRadioSelection, this.CanChangeRadioSelection);
this.ResetRadioSelectionCommand = new DelegateCommand(this.OnResetRadioSelection, this.CanResetRadioSelection);
}
public ICommand ChangeRadioSelectionCommand { get; private set; }
private void OnChangeRadioSelection(string radioSelection)
{
RadioSelection = radioSelection;
}
private bool CanChangeRadioSelection(string radioSelection) { return true; }
public ICommand ResetRadioSelectionCommand { get; private set; }
private void OnResetRadioSelection()
{
RadioSelection = "Item1";
}
private bool CanResetRadioSelection() { return true; }
}
这会改变 radioSelection,但不会反映在 gui 中。有没有办法做到这一点?或者也许只是处理单选按钮的更好方法?
【问题讨论】:
标签: c# wpf mvvm data-binding prism