将 ComboBox TwoWay 绑定到 属性

Binding ComboBox TwoWay to Property

我正在尝试让我的双向绑定工作。

这些 ComboBoxes 应该将它们自己(TwoWay)绑定到它们在 VM 中的 属性:

<ComboBox x:Name="_cmbCatT1" Margin="5,1,5,10" 
          ItemsSource="{Binding MVM.CategoryLinkCollection}"
          DisplayMemberPath="Category.Name" 
          SelectedValue="{Binding MVM.SelectedTier1, Mode=TwoWay}" 
          SelectedValuePath="Category"/>
<ComboBox x:Name="_cmbCatT2" Margin="5,1,5,10" 
          DataContext="{Binding SelectedItem, ElementName=_cmbCatT1}" 
          ItemsSource="{Binding CategoryLinkCollection}" 
          DisplayMemberPath="Category.Name" 
          SelectedValue="{Binding MVM.SelectedTier2, ElementName=_vManipulation, Mode=TwoWay}" 
          SelectedValuePath="Category"/>
<ComboBox x:Name="_cmbCatT3" Margin="5,1,5,10" 
          DataContext="{Binding SelectedItem, ElementName=_cmbCatT2}" 
          ItemsSource="{Binding CategoryLinkCollection}" 
          DisplayMemberPath="Category.Name" 
          SelectedValue="{Binding MVM.SelectedTier3, ElementName=_vManipulation, Mode=TwoWay}" 
          SelectedValuePath="Category"/>

虚拟机:

private string selectedName;
public string SelectedName {
    get {
        return this.selectedName;
    }
    set {
        this.selectedName = value;
        OnPropertyChanged("SelectedName");
    }
}
private string selectedDescription;
public string SelectedDescription {
    get {
        return this.selectedDescription;
    }
    set {
        this.selectedDescription = value;
        OnPropertyChanged("SelectedDescription");
    }
}
private string selectedRemark;
public string SelectedRemark {
    get {
        return this.selectedRemark;
    }
    set {
        this.selectedRemark = value;
        OnPropertyChanged("SelectedRemark");
    }
}
private string selectedValue; 
public string SelectedValue {
    get {
        return this.selectedValue;
    }
    set {
        this.selectedValue = value;
        OnPropertyChanged("SelectedValue");
    }
}
private Model.Room selectedRoom;
public Model.Room SelectedRoom {
    get {
        return this.selectedRoom;
    }
    set {
        this.selectedRoom = value;
        OnPropertyChanged("SelectedRoom");
    }
}
private Model.Locker selectedLocker;
public Model.Locker SelectedLocker {
    get {
        return this.selectedLocker;
    }
    set {
        this.selectedLocker = value;
        OnPropertyChanged("SelectedLocker");
    }
}
private Model.Category selectedTier1;
public Model.Category SelectedTier1 {
    get {
        return this.selectedTier1;
    }
    set {
        this.selectedTier1 = value;
        OnPropertyChanged("SelectedTier1");
    }
}
private Model.Category selectedTier2;
public Model.Category SelectedTier2 {
    get {
        return this.selectedTier2;
    }
    set {
        this.selectedTier2 = value;
        OnPropertyChanged("SelectedTier2");
    }
}
private Model.Category selectedTier3;
public Model.Category SelectedTier3 {
    get {
        return this.selectedTier3;
    }
    set {
        this.selectedTier3 = value;
        OnPropertyChanged("SelectedTier3");
    }
}
private Model.Manufacturer selectedManufacturer;
public Model.Manufacturer SelectedManufacturer {
    get {
        return this.selectedManufacturer;
    }
    set {
        this.selectedManufacturer = value;
        OnPropertyChanged("SelectedManufacturer");
    }
}

请注意 ItemsSource 的数据类型是“CategoryLinkCollection”,它包含一个“Category”-属性 和一个 Obs.Collection 的“CategoryLinkCollection”。通过 SelectedValuePath,“类别”被“保存”在虚拟机的 属性 中。

只要我 select ComboBox 中的一个 Item 一切正常,但是 当我手动设置 VM-Properties 时,ComboBoxes 不会预 select ItemsSource 中包含已定义类别的 Item。正常的字符串值就可以找到(文本框)

我认为它永远不会工作,因为类型不同(ComboBox = CategoryLinkCollection with ValuePath to Category,属性 = Category)但也许你们中的一些人可以证明我错了。如果您需要更多信息,请告诉我。

更新 1:

我只记得主要原因应该在其他地方,因为模型“制造商”没有包装器 - 因此 ItemsSource 包含与 属性 相同数据类型的集合。

XAML:

<ComboBox x:Name="_cmbManufacturer" 
          ItemsSource="{Binding MVM.ManufacturerCollection}" 
          DisplayMemberPath="Name" 
          SelectedItem="{Binding MVM.SelectedManufacturer, Mode=TwoWay}"/>

虚拟机: 见上文。

更新二:

首先请远离那些蹩脚的类别并转到更新 1 中提到的制造商,因为它是相同的问题但更容易进入。

我现在在手动设置后检查 SelectedManufacturer-属性 以防万一设置时出现一些问题。 SelectedManufacturer-属性 包含制造商(非空),但 UI 仍未更新。

更新 3:

使用诊断 NS 后,我从 Output-Window 中得到以下输出:

System.Windows.Data Warning: 60 : BindingExpression (hash=43478430): Default mode resolved to TwoWay

System.Windows.Data Warning: 61 : BindingExpression (hash=43478430): Default update trigger resolved to PropertyChanged

System.Windows.Data Warning: 62 : BindingExpression (hash=43478430): Attach to System.Windows.Controls.ComboBox.SelectedItem (hash=10372298)

System.Windows.Data Warning: 67 : BindingExpression (hash=43478430): Resolving source

System.Windows.Data Warning: 70 : BindingExpression (hash=43478430): Found data context element: ComboBox (hash=10372298) (OK)

System.Windows.Data Warning: 78 : BindingExpression (hash=43478430): Activate with root item Manipulation (hash=64100268)

System.Windows.Data Warning: 107 : BindingExpression (hash=43478430): At level 0 using cached accessor for Manipulation.MVM: RuntimePropertyInfo(MVM)

System.Windows.Data Warning: 104 : BindingExpression (hash=43478430): Replace item at level 0 with Manipulation (hash=64100268), using accessor RuntimePropertyInfo(MVM)

System.Windows.Data Warning: 101 : BindingExpression (hash=43478430): GetValue at level 0 from Manipulation (hash=64100268) using RuntimePropertyInfo(MVM): ManipulationViewModel (hash=11088040)

System.Windows.Data Warning: 108 : BindingExpression (hash=43478430): At level 1 - for ManipulationViewModel.SelectedManufacturer found accessor RuntimePropertyInfo(SelectedManufacturer)

System.Windows.Data Warning: 104 : BindingExpression (hash=43478430): Replace item at level 1 with ManipulationViewModel (hash=11088040), using accessor RuntimePropertyInfo(SelectedManufacturer)

System.Windows.Data Warning: 101 : BindingExpression (hash=43478430): GetValue at level 1 from ManipulationViewModel (hash=11088040) using RuntimePropertyInfo(SelectedManufacturer): Manufacturer (hash=14500136)

System.Windows.Data Warning: 80 : BindingExpression (hash=43478430): TransferValue - got raw value Manufacturer (hash=14500136)

System.Windows.Data Warning: 84 : BindingExpression (hash=43478430): TransferValue - implicit converter produced Manufacturer (hash=14500136)

System.Windows.Data Warning: 89 : BindingExpression (hash=43478430): TransferValue - using final value Manufacturer (hash=14500136)

更新四:

制造商Class:

public class Manufacturer : Base.SqlBase {
    public Manufacturer(int id, string name) {
        this.SqlID = id;
        this.Name = name;
    }
}

SqlBase Class:

public abstract class SqlBase : INotifyPropertyChanged {
    public int SqlID { get; set; }
    private string _name;
    public string Name {
        get {
            return _name;
        }
        protected set {
            this._name = value;
            PropertyChangedHandler("Name");
        }
    }

    public void SetId(int id) {
        this.SqlID = id;
        PropertyChangedHandler("SqlID");
    }

    private void PropertyChangedHandler(string propertyName) {
        PropertyChangedEventHandler temp = PropertyChanged;
        if (temp != null) {
            temp(this, new PropertyChangedEventArgs(propertyName));
        }
    }

    public event PropertyChangedEventHandler PropertyChanged;
}

实体Class:

public class Entity : Base.SqlBase {

    public string Description { get; private set; }
    public string Remark { get; private set; }
    public int Value { get; private set; }
    public Model.CategoryWrapper Categories { get; private set; }
    public Model.Manufacturer Manufacturer { get; private set; }
    public Model.Locker Locker { get; private set; }

    public Entity(string name, string desc, string remark, int value, Model.CategoryWrapper cat, Model.Manufacturer manuf, Model.Locker locker) {           
        this.Name = name;
        this.Description = desc;
        this.Remark = remark;
        this.Value = value;
        this.Categories = cat;
        this.Manufacturer = manuf;
        this.Locker = locker;
    }

    public Entity(int id, string name, string desc, string remark, int value, Model.CategoryWrapper cat, Model.Manufacturer manuf, Model.Locker locker) {
        this.SqlID = id;
        this.Name = name;
        this.Description = desc;
        this.Remark = remark;
        this.Value = value;
        this.Categories = cat;
        this.Manufacturer = manuf;
        this.Locker = locker;
    }
}

我获得了 GridView(类型:实体)的 SelectedItem,并将其交给我的 Manipulation-View,后者实例化了它的 ViewModel。在这个 ViewModel 中,实体被分成它的部分(例如制造商)和属性(例如 SelectedManufacturer)得到设置。所有这些步骤都在 视图构建之前执行(在 Initializecomponent 之前)。我以这种方式认为 View 在初始化时必须获得 selected 值 - 或者我错了吗?

更新5:

我真的不知道为什么,但是当 Window 初始化时设置制造商时,制造商对象的 属性Changed-属性 为 null - 当我设置制造商通过 selecting 一个项目 属性 不为空。

在绑定中使用更新源触发器 属性 并将其设置为 PropertyChanged:

<ComboBox x:Name="_cmbManufacturer" ItemsSource="{Binding MVM.ManufacturerCollection}" DisplayMemberPath="Name" SelectedItem="{Binding MVM.SelectedManufacturer, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}"/>

Howsit Chill-X,我是否正确理解核心问题是您希望组合框在更新 viewModel 时反映更改的 selection?如果是这样,这里是您如何做到这一点的简化版本。

需要注意的重要事项(将 selected 项目绑定到另一个名为 SelectedCategory 的 属性。当您更改 SelectedCategory 在 VM 中,UI 将更改,如果您 select 组合框中的新项目,则 SelectedCategory 属性 将是已更新。

这是视图模型:

public class ViewModel : INotifyPropertyChanged
{
    private ObservableCollection<Category> _categoryLinkCollection;
    public ObservableCollection<Category> CategoryLinkCollection
    {
        get
        {
            return this._categoryLinkCollection;
        }
        set
        {
            if (value != this._categoryLinkCollection)
            {
                this._categoryLinkCollection = value;
                OnPropertyChanged("CategoryLinkCollection");
            }
        }
    }

    private Category _selectedCategory;
    public Category SelectedCategory
    {
        get
        {
            return this._selectedCategory;
        }
        set
        {
            this._selectedCategory = value;
            OnPropertyChanged("SelectedCategory");
        }
    }
}

这是xaml:

<ComboBox ItemsSource="{Binding CategoryLinkCollection, Mode=TwoWay}" DisplayMemberPath="Name" SelectedItem="{Binding SelectedCategory, Mode=TwoWay}" />

我只是使用页面隐藏代码将虚拟数据添加到集合中(在 window_loaded 上单击按钮以显示您可以更新 VM 属性 和 UI更新。

public partial class MainWindow : Window
{
    public MainWindow()
    {
        InitializeComponent();

        // Set the View's DataContext to our ViewModel
        var vm = new ViewModel();
        this.DataContext = new ViewModel();
    }

    private void Window_Loaded(object sender, RoutedEventArgs e)
    {
        // Populate Category Collection with dummy data.
        var vm = ((ViewModel)this.DataContext);
        vm.CategoryLinkCollection = new ObservableCollection<Category>()
        {
            new Category("Cat 1"),
            new Category("Cat 2"),
            new Category("Cat 3"),
            new Category("Cat 4"),
            new Category("Cat 5"),
            new Category("Cat 6"),
        };
        vm.SelectedCategory = vm.CategoryLinkCollection[0];
    }

    private void btn_Click(object sender, RoutedEventArgs e)
    {
        var vm = ((ViewModel)this.DataContext);
        vm.SelectedCategory = vm.CategoryLinkCollection[3];
    }
}

现在您有一个 ComboBox,它从 VM 和 UI 更新。

我好像解开了谜底

解释:

"Manipulation"- 视图,它应该 pre-select 实体给出的 ComboBox-Value 将接收它自己的 Observable 实例 Collection - 但 Manufacturer-Object 被传递给那个表单 - 所以它不包含在 Collection.

解法:

覆盖 Equals-Method 检查 SQLID 属性 而不是默认方法来确定相等性解决了问题。