0

我有一个组合框,其中包含 Country 对象的集合作为它的源(它绑定到视图模型中的 Country 属性)。

Country 组合显示在用户表单的一部分上。用户表单由用户对象填充。一个用户对象只拥有一个 CountryID(即 Country 的外键)。我目前通过将名称文本框绑定到我的用户对象中的名称属性等来填充我的用户表单。但是,当我来到 Country 组合绑定时,我真的被卡住了。

我对 Combo 的绑定是:

ItemsSource="{Binding Countries}" DisplayMemberPath="CountryDescription" 

那么对于当前加载的用户,我需要获取他们的 Country ID 并将其绑定到 Country 组合吗?我该怎么做,因为国家组合没有整数列表,而是国家对象列表。我虽然关于使用转换器,但这似乎有点矫枉过正,因为该组合在其源中有一个国家对象以及我想要的相应 CountryID。

那么有没有办法让用户 CountryID 属性绑定到 Country 组合并让 Country 组合到友好的用户名?我需要两种方式绑定,因为用户需要能够选择不同的国家,然后应该更新用户对象中相应的 countryID 属性。

非常感谢任何帮助!干杯...

编辑

这是我所拥有的精简版(为了清楚起见,我省略了所有 notifypropertychanged 代码)

class User
{
    public int UserID 
    {
        get;set;
    }

    public string Username
    {
        get;set;
    }

    public int CountryID
    {
        get;set;
    }
}

class Country
{
    public int CountryID
    {
        get;set;
    }

    public string CountryDescription
    {
        get;set;
    }
}

我的视图模型有一个 Country 属性,它只是 Country 对象的列表(如上所示的绑定)。该视图有一个用户名文本框和一个显示国家描述的组合框。我的视图模型有一个“用户”属性供视图绑定。用户名的绑定是:

<TextBox x:Name="NameBox" Text=" {Binding User.Username, Mode=TwoWay}"   
DataContext="{Binding}" />

我遇到的问题是国家组合的选定项目的绑定。假设我在组合中有 2 个国家/地区对象,如下所示:

CountryID = 1, CountryDescription = "法国" CountryID = 2, CountryDescription = "西班牙"

用户设置为:

用户 ID = 1,用户名 =“鲍勃”,国家 ID = 1。

该组合需要显示“法国”。但是如果用户将 France 更改为 Spain,则用户的 CountryID 需要更改为 2。

4

2 回答 2

0

基本上你需要一个 ValueMemberPath ,它确实存在于组合框上大概是因为他们认为不需要它

相反,组合框中的每个项目都绑定到 Country 项目,因此您真正需要的是一个将Country对象转换为 ID 号/int 的值转换器(如果您需要两种方式,则再次返回,否则下面的代码将完成这项工作) .

例如:

public class CountryConverter : IValueConverter
{
    public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
    {
        Country country = (Country)value;
        return country.CountryId;
    }

    public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
    {
        /// Not sure yet the best way to get the correct Country object instance, unless you can attach it to the convertor, pass it as a ConvertorParameter or just make it global. :)
    }
}

双向的问题在于,要将数字转换回 Country 对象的正确实例,您需要访问控件使用的 Country 对象的实际列表。

无论如何:然后您只需将 ComboBox 的 SelectedItem 绑定到 User.CountryID 属性(当然也指定转换器)。

<TextBox x:Name="NameBox" SelectedItem={Binding User.CountryID, Convertor={StaticResource CountryConverter}} Text="{Binding User.Username, Mode=TwoWay}" DataContext="{Binding}" />

并在页面资源中声明转换器,例如:

<UserControl.Resources>
  <local:CountryConverter x:Key="CountryConverter" />
</UserControl.Resources>
于 2012-07-03T13:08:13.533 回答
0
private Country _SelectedCountry;
public Country SelectedCountry
{
    get
    {
        return _SelectedCountry;
    }

    set
    {
        if(value != null && value != _SelectedCountry)
        { 
            if(User.CountryID != value.CountryID) 
                User.CountryID = value.CountryID;
            _SelectedCountry = value;
        }
    }
}

不要忘记在所有需要的地方放置 RaisePropertyChanged。如果您对此有任何理解问题,请告诉我。

于 2012-07-03T13:18:30.527 回答