我有一个这样的视图模型:
public class BaseViewModelTech : INotifyPropertyChanged
{
static string _TechnicianID;
public string TechnicianID
{
get {
return _TechnicianID;
}
set {
_TechnicianID = TechnicianID;
OnPropertyChanged("TechnicianID");
}
}
static string _DeviceID;
public string DeviceID
{
get
{
return _DeviceID;
}
set
{
_DeviceID = DeviceID;
OnPropertyChanged("DeviceID");
}
}
// In ViewModelBase.cs
public event PropertyChangedEventHandler PropertyChanged;
protected virtual void OnPropertyChanged(string propertyName)
{
this.VerifyPropertyName(propertyName);
PropertyChangedEventHandler handler = this.PropertyChanged;
if (handler != null)
{
var e = new PropertyChangedEventArgs(propertyName);
handler(this, e);
}
}
[Conditional("DEBUG")]
[DebuggerStepThrough]
public void VerifyPropertyName(string propertyName)
{
// Verify that the property name matches a real,
// public, instance property on this object.
if (TypeDescriptor.GetProperties(this)[propertyName] == null)
{
string msg = "Invalid property name: " + propertyName;
Debug.Fail(msg);
}
}
}
我将它作为参数发送到我的xaml.cs
public partial class BaseView : Window{
BaseViewModelTech viewModel;
public BaseView (BaseViewModelTech vm)
{
InitializeComponent();
viewModel = vm;
}}
我写什么来通过xaml使用绑定来访问它?我没有理解多个例子。
答案 0 :(得分:2)
稍微更改您的视图后面的代码:
public partial class BaseView : Window
{
BaseViewModelTech viewModel;
public BaseView (BaseViewModelTech vm)
{
InitializeComponent();
viewModel = vm;
this.DataContext = vm; // <----------- add this
}
}
然后在你的XAML中你可以得到这样的东西:
<TextBlock Text="{Binding TechnicianID}" />
另请注意,在您的二传手中,您希望在>>更改属性值之后执行通知,而不是之前:
set
{
_DeviceID = DeviceID;
OnPropertyChanged("DeviceID"); // <------ this goes after the member variable change
}
答案 1 :(得分:1)
在您的情况下,由于vm实例是View的成员,因此您无法直接将ViewModel直接引用到xaml中。因此,您应该首先在代码隐藏中设置视图的DataContext:
public partial class BaseView : Window{
BaseViewModelTech viewModel;
public BaseView (BaseViewModelTech vm)
{
InitializeComponent();
viewModel = vm;
this.DataContext=viewModel;
}}
然后在我的xaml.xaml中为例如标签:
<Label Content="{Binding TechnicianID }"/>