组合框双向绑定重置属性

Combo Box Two Way Binding resets Properties

我在 activity 中的数据网格中有一个组合框。基于组合框选择,我以编程方式使用控件填充另一个网格。用户在这些控件中输入一些数据,然后保存。组合框绑定的对象有很多属性,其中两个用于选择值路径和显示成员路径。数据使用组合框的两种方式绑定。重新打开已保存在工作流上的 activity 时,数据会重新正确加载,并且在组合框中设置了正确的对象值。但是在 UI 渲染时,只有组合框附加的值保持不变(即选定值路径和显示成员路径中的值),其余值将被重置。

知道为什么会这样吗?

P.S: 将绑定设置为 OneTime 解决了检索问题,但加载后对 UI 所做的任何更改不会反射回来。

代码隐藏:

public ObservableCollection<MyRule> AllRules {get;set;}
public MyRule myRule{get;set;}

在数据网格加载事件中,我将 AllRules 填充为:

AllBusinessRules.Add(new MyRule () { RuleId = item.Id, RuleName = item.Name});

其中 item.Iditem.Name 是通过服务调用从数据库中获取的。

在同一事件中,如果我还加载任何以前保存的规则为:

myRule=SelectedRule; 

其中 SelectedRule 也有 RuleId, RuleName, Inputs and Outputs

代码:

     <ComboBox  
        ItemsSource="{Binding Path=AllRules}"
       SelectedItem="{Binding Path=myRule,UpdateSourceTrigger=PropertyChanged,Mode=TwoWay}"
        SelectedValuePath="RuleId" 
        DisplayMemberPath="RuleName">
        <DataTemplate>
            <TextBox Text="{Binding Path=myRule.RuleName}"/>
        </DataTemplate>

    </ComboBox>

Class:

  public class MyRule{
    public int RuleId{get;set;}
    public string RuleName{get;set;}
    public List<string> Inputs{get;set;}   //properties that are reset when the UI renders
    public List<string> Outputs{get;set;}  //properties that are reset when the UI renders
    
    }

输入和输出属性通过反射从以编程方式生成的控件中获取,并添加到由组合框填充并保存的对象中。

我研究过这个问题here但是解决方案没有解决我的问题。任何帮助都会很棒。

SelectedValuePathDisplayMemberPath设置错误。 DisplayMemberPath 应该是 "RuleName"。 SelectedValueSelectedValuePath不需要,因为你设置了SelectedItem。由于BindingSelectedItem 将自动获得选择的项目。您可以从 myRule 对象访问其他属性。

我花了很多时间来调查问题所在,但现在我知道这很简单。

正如我所展示的,在数据​​网格的 Loaded 事件中,我曾经设置组合框的 ItemsSource,而在项目源中,我只设置了属性 RuleIdRuleName.

问题: 所以问题是当我分配值时,即重新加载组合框时选择的值,例如myRule=SelectedRule ItemsSource 中没有其他属性,即输入和输出。这就是为什么所选对象虽然正确但没有输入和输出,因为 SelectedItem 来自组合框的 ItemsSource,给我的印象是双向绑定以某种方式重置了未与组合框绑定的属性的值。

解法: 最后,我将 MyRule 对象包装在另一个对象中,例如 RuleInformation

public class RuleInformation{
public List<string>  Inputs;
public List<string>  Outputs;
public MyRule myRule{get;set;} 

}

其中 MyRule 类似于:

public class MyRule{
public int RuleId{get;set;}
public string RuleName{get;set;}
}

因此组合框绑定到 MyRule 对象,而上层对象的输入和输出属性保持不变。