[英]My MVVM pattern is not working… Why?
在这个例子中,我尝试开发一个简单的工具来管理客户的软件许可证。 它在C#WPF中实现,中心设计模式基于MVVM范例(使用INotifyPropertyChanged,ICommand和其他东西分离表示和逻辑/数据层)。
为什么XAML中属性的动态绑定不可能? 请查看最后附带的链接以获取更多信息。
谢谢您的帮助!
费利克斯
我认为的相关部分(XAML):
<DataGrid ItemsScource="{Binding Licenses}" SelectedItem="{Binding SelectedLicense}">
<DataGrid.Columns>
<DataGridTextColumn Binding="{Binding CustomerConverted}" Header="Customer"/>
<DataGridTextColumn Binding="{Binding LicenseNoConverted}" Header="License no."/>
<DataGridTextColumn Binding="{Binding LicenseKey}" Header="License key"/>
<DataGridTextColumn Binding="{Binding LastActivation}" Header="Last activated ver."/>
<DataGridTextColumn Binding="{Binding TypeConverted}"/>
</DataGrid.Columns>
</DataGrid>
代码隐藏
public partial class WMain : Window {
public WMain() {
InitializeComponent();
//construct ViewModel (works fine, all properties are consistent)
WMainCtrl ctrl = new WMainCtrl();
//set data context in code behind (XAML-bindings are not working)
this.DataContext = ctrl;
//that works instead... why?
//c_dgLicenses.ItemsSource = ctrl.Licenses;
}
}
视图模型:
public class WMainCtrl : BaseCtrl {
public WMainCtrl() {
try {
//init data
License.selectAndConvertData();
} catch (Exception exc) {
throw exc;
}
}
//this works, the collection is definitely filled
internal ObservableCollection<License> Licenses { get { return License.Obscol; } }
private License _selectedLicense;
public License SelectedLicense {
get {
if (_selectedLicense == null) {
if (Licenses.Count == 0) {
return null;
}
return Licenses[0];
} else
return _selectedLicense;
}
set {
if (_selectedLicense != value) {
_selectedLicense = value;
try {
Console.WriteLine(SelectedLicense.LicenseKey);
} catch (Exception) {}
OnPropertyChanged();
}
}
}
}
ViewModelBase的相关部分:
protected void OnPropertyChanged([CallerMemberName] string propertyName = null) {
PropertyChangedEventHandler handler = PropertyChanged;
if (handler != null) {
handler(this, new PropertyChangedEventArgs(propertyName));
}
}
public event PropertyChangedEventHandler PropertyChanged;
以下是一些详细信息:
您在DataGrid上输入了错误的ItemsSource:
DataGrid ItemsScource =“{Binding Licenses}”SelectedItem =“{Binding SelectedLicense}”
我的旧ViewModel属性(不工作)
internal ObservableCollection<License> Licenses { get { return License.Obscol; } }
我的新ViewModel属性(正常工作)
public ObservableCollection<License> Licenses { get { return License.Obscol; } }
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.