在此示例中,我尝试开发一个简单的工具来管理客户的软件许可证。它在C#WPF中实现,中央设计模式基于MVVM范例(使用INotifyPropertyChanged,ICommand和其他东西分离表示和逻辑/数据层)。

为什么无法在XAML中动态绑定(bind)属性?
请查看结尾处的链接以获取更多信息。

谢谢您的帮助!

费利克斯

我的观点(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;
    }
}

ViewModel:
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;

以下是一些详细信息:

Architecture (rough draft, no UML rules)

Screenshot: DataContext is set properly?!

最佳答案

您在DataGrid上输错了ItemsSource:

DataGrid ItemsScource =“{Binding Licenses}” SelectedItem =“{Binding SelectedLicense}”

关于c# - 我的MVVM模式不起作用...为什么?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/36622787/

10-17 03:10