-1

我有一个绑定到类 SInstance 的属性 LogicalP 的 wpf 组合框。组合框的 ItemSource 是一个字典,其中包含 LogicalP 类型的项。

如果我将 SInstance 中的 LogicalP 设置为初始状态,则组合框文本字段显示为空。如果我选择下拉菜单,我所有的字典值都在那里。当我更改 SInstance 中的选择 LogicalP 时,会正确更新。如果我在 C# 中更改 Sinstance,则相应的组合框值不会反映下拉菜单中更新的 LogicalP。

我已经将绑定模式设置为双向,但没有运气。有什么想法吗?

我的 Xaml:

<UserControl.Resources>
<ObjectDataProvider x:Key="PList"
                    ObjectType="{x:Type src:MainWindow}"
                    MethodName="GetLogPList"/>
</UserControl.Resources>

<DataTemplate DataType="{x:Type src:SInstance}">
<Grid>
    <ComboBox ItemsSource="{Binding Source={StaticResource PList}}"
              DisplayMemberPath ="Value.Name" 
              SelectedValuePath="Value"
            SelectedValue="{Binding Path=LogicalP,Mode=TwoWay}">
    </ComboBox>
</Grid>
</DataTemplate>

我的C#:

public Dictionary<string, LogicalPType> LogPList { get; private set; }
public Dictionary<string, LogicalPType> GetLogPList()
{
    return LogPList;
}

public class LogicalPType
{
    public string Name { get; set; }
    public string C { get; set; }
    public string M { get; set; }
}                  

public class SInstance : INotifyPropertyChanged
{
    private LogicalPType _LogicalP;

    public string Name { get; set; }
    public LogicalPType LogicalP
    {
        get { return _LogicalP; }
        set
        {
            if (_LogicalP != value)
            {
                _LogicalP = value;
                NotifyPropertyChanged("LogicalP");
            }
        }
    }

    #region INotifyPropertyChanged Members
    #endregion
}    
4

2 回答 2

0

他们看的不是同一个来源。
您需要让 SInstance 同时提供 LogPList 和 LogicalP。

_LogicalP 未连接到 LogPList

如果你想让不同的对象比较相等,那么你需要覆盖 Equals。

于 2013-06-04T18:29:35.300 回答
0

这是我的工作解决方案。通过将字典检索 GetLogPList 移动到与提供数据的类相同的类(如 Blam 建议的那样),我能够使绑定以两种方式工作。我将绑定更改为列表而不是字典以简化组合框

下面是更新后的 Xaml,显示了新的 ItemsSource 绑定和 SelectedValuePath 的删除:

<DataTemplate DataType="{x:Type src:SInstance}">
    <Grid>
        <ComboBox ItemsSource="{Binding GetLogPList}"
                  DisplayMemberPath ="Name" 
                SelectedValue="{Binding Path=LogicalP,Mode=TwoWay}">
        </ComboBox>
    </Grid>
</DataTemplate>

然后我将字典 LogPList 更改为静态,以便类 SInstance 可以访问它:

    public static Dictionary<string, LogicalPType> LogPList { get; private set; }

最后,我将 GetLogPList 作为属性移到了类 SInstance 中。再次注意它返回一个列表而不是字典,以使 Xaml 更简单一些:

public class SInstance : INotifyPropertyChanged
{
    public List<LogicalPType> GetLogPList
    {
        get { return MainWindow.LogPList.Values.ToList(); }
        set { }
    }   

    private LogicalPType _LogicalP;

    public string Name { get; set; }
    public LogicalPType LogicalP
    {
        get { return _LogicalP; }
        set
        {
            if (_LogicalP != value)
            {
                _LogicalP = value;
                NotifyPropertyChanged("LogicalP");
            }
        }
    }

    #region INotifyPropertyChanged Members
    #endregion
} 
于 2013-06-05T17:20:28.563 回答