ComboBox绑定到多个DataContext

时间:2016-06-13 21:34:32

标签: c# wpf data-binding

我的应用程序中有一个组合框控件。我正在使用它从数据库中定义的状态列表中选择状态。所选值应该用于为用户类的状态字段(即a)赋值(我有一个表在数据库中维护用户数据)。

XAML:

<StackPanel x:Name="stckDetails">
    <TextBox Margin="10,5,10,5" Text="{Binding FirstName, Mode=TwoWay}"/>
    <TextBox Margin="10,5,10,5" Text="{Binding LastName, Mode=TwoWay}"/>
    <ComboBox Margin="10,5,10,5" ItemsSource = "{Binding Register.States}" Text="{Binding State, Mode=TwoWay}"/>
</StackPanel>

代码背后:

class Register
{
  public User newUser;
  public ObservableCollection<string> States { get; set; }
  public Register()
  {
    newUser = new User();
    States = new ObservableCollection<string> { "CH", "MA", "KL", "FL" };
    stckDetails.DataContext = newUser;
  }
}


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

    public string FirstName { get; set; }
    public string LastName { get; set; }
    public string State {get; set; }
 }

如何将组合框的不同属性绑定到不同的DataContext。可能吗 ?我正在使用的语法不起作用。

1 个答案:

答案 0 :(得分:0)

我做了一些改变。请参阅下面的代码。

<Window x:Class="DataContext_Learning.MainWindow"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
    xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
    xmlns:local="clr-namespace:DataContext_Learning"
    mc:Ignorable="d"
    Title="MainWindow" Height="350" Width="525">
<Grid>
    <StackPanel x:Name="stckDetails">
        <TextBox Margin="10,5,10,5" Text="{Binding NewUser.FirstName, Mode=TwoWay}"/>
        <TextBox Margin="10,5,10,5" Text="{Binding NewUser.LastName, Mode=TwoWay}"/>
        <ComboBox Margin="10,5,10,5" ItemsSource = "{Binding States}" Text="{Binding State, Mode=TwoWay}"/>
    </StackPanel>
</Grid>

    namespace DataContext_Learning
{
    /// <summary>
    /// Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class MainWindow : Window
    {
        public MainWindow()
        {
            InitializeComponent();
            this.DataContext = new Register();
        }
    }

    class Register
    {
        public User NewUser { get; set; }
        public ObservableCollection<string> States { get; set; }
        public Register()
        {
            NewUser = new User();
            States = new ObservableCollection<string> { "CH", "MA", "KL", "FL" };
        }
    }


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

        public string FirstName { get; set; }
        public string LastName { get; set; }
        public string State { get; set; }
    }
}