WPF数据绑定到组合框

时间:2014-05-17 19:57:27

标签: c# wpf data-binding

我遇到了与组合框的数据绑定问题。其他绑定工作正常。有人能告诉我这里我做错了吗。

 class Bank
    {
        public string bankcode{get; set;}
        public string bankname { get; set; }    
        public ObservableCollection <BankBranch> branches;

    }
    class BankBranch
    {
        public string branchcode { get; set; }
        public string branchname { get; set; }
    }

            Bank b = new Bank{
                bankcode="1",
                bankname="Bank1",
                branches = new ObservableCollection<BankBranch>(){
                    new BankBranch(){branchcode="11", branchname="Location1"},
                    new BankBranch(){branchcode="11", branchname="Location12"}
                },

            };
            bankpanel.DataContext = b;


<StackPanel x:Name="bankpanel">
        <StackPanel Orientation="Horizontal">
            <TextBlock >Bank Code</TextBlock>
            <TextBox Text="{Binding bankcode}" Width="100"/>
        </StackPanel>
        <StackPanel Orientation="Horizontal">
            <TextBlock >Bank Name</TextBlock>
            <TextBox Text="{Binding bankname}" Width="100"/>
        </StackPanel>
        <StackPanel Orientation="Horizontal">
            <TextBlock >Bank Branches</TextBlock>

            <ComboBox ItemsSource="{Binding branches}" DisplayMemberPath="branchname" 
 SelectedValuePath="branchname" 
 Width="100">

            </ComboBox>
        </StackPanel>
    </StackPanel>

2 个答案:

答案 0 :(得分:2)

使branches属性。它目前是一个领域。所有绑定必须通过属性。

答案 1 :(得分:2)

您应该绑定到不属于字段的属性。

在您的情况下,branches被声明为字段。

请尝试以下代码:

class Bank
{
    public string bankcode { get; set; }
    public string bankname { get; set; }
    public ObservableCollection<BankBranch> branches { get; set; }
}