我如何将 View 模型中的 bool 值传递给 View 并更改值。
例如在我的 View 模型中,我创建了一个 bool
public bool load
{
get { return m_load; }
set
{
m_load = value;
OnPropertyChanged(this, o => o.load);
}
}
然后我有我的
SelectedVm
代码public ViewModel SelectedVm
{
get { return _selectedVm; }
set
{
_selectedVm = value;
if (_selectedVm != null && load == true)
{
_selectedVm.Load();
}
Load = false;
OnPropertyChanged(this, o => o.SelectedVm);
}
}
在我看来
SelectedVm
被绑定(bind)了两次,但我只想在其中一个绑定(bind)上调用 Load,因此需要更改 bool load
所以在我看来,如果我有以下
<ListView Grid.Row="1" Name="Sample"
ItemsSource="{Binding Path=SampleViewModel}"
SelectedItem="{Binding SelectedVm, Mode=TwoWay}"
IsSynchronizedWithCurrentItem="True" Width="500">
</ListView>
我如何更改
bool
加载为真或假以上所有只是快速示例,我认为这可能很简单,但是我不习惯
WPF
我还在学习。任何建议都会很棒
最佳答案
好的,如果你想在 View 中获取 Load 的值并且你想在纯 MVVM 模式中执行它,那么在 View 中创建 bool 类型的 DependencyProperty 并将其绑定(bind)到 VM 的 Load 属性,如
public partial class MainWindow : Window
{
public static readonly DependencyProperty LoadProperty = DependencyProperty.Register("MyCustom", typeof(bool), typeof(MainWindow), new PropertyMetadata(new PropertyChangedCallback(LoadPropertyChangedCallback)));
public bool Load
{
get
{
return (bool)this.GetValue(LoadProperty) ;
}
set
{
this.SetValue(LoadProperty, value);
}
}
static void LoadPropertyChangedCallback(DependencyObject d, DependencyPropertyChangedEventArgs e)
{
//Do your load stuff here
}
public MainWindow()
{
InitializeComponent();
this.SetBinding(LoadProperty, new Binding("load"));
DataContext = new ViewModel();
}
}
public class ViewModel : INotifyPropertyChanged
{
public ViewModel()
{
load = true;
}
bool m_load;
public bool load
{
get { return m_load; }
set
{
m_load = value;
OnPropertyChanged("load");
}
}
public event PropertyChangedEventHandler PropertyChanged;
private void OnPropertyChanged(string propName)
{
if (PropertyChanged != null)
PropertyChanged(this, new PropertyChangedEventArgs(propName));
}
}
关于c# - WPF 将 bool 值传递给 View 并更改它,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18062063/