Silverlight combobox SelectedItem绑定问题

时间:2011-06-27 09:52:00

标签: c# silverlight-4.0 combobox

我是.NET新手,正在开发我的第一个Silverlight应用程序。

我有一个Silverlight子窗口,用于将新客户添加到gridview,并具有以下代码:

namespace FrontEnd.Views
{
    public partial class NewCustomer : ChildWindow
    {
        public DataTransfer.Customer MyCustomer { get; set; }

        public NewCustomer()
        {
            InitializeComponent();
            MyCustomer = new DataTransfer.Customer();
            NewCustomerForm.CurrentItem = MyCustomer;
            NewCustomerForm.BeginEdit();
        }

        private void OKButton_Click(object sender, RoutedEventArgs e)
        {
            NewCustomerForm.CommitEdit();
            this.DialogResult = true;
        }

        private void CancelButton_Click(object sender, RoutedEventArgs e)
        {
            MyCustomer = null;
            NewCustomerForm.CancelEdit();
            this.DialogResult = false;
        }
    }
}



<dataform:DataForm x:Name="NewCustomerForm" Header="New Customer" AutoGenerateFields="False" Margin="0,12,0,0" MinWidth="290" HorizontalAlignment="Left">
            <dataform:DataForm.EditTemplate>
                <DataTemplate>
                    <StackPanel>
                        <dataform:DataField Label="First name">
                            <TextBox Text="{Binding Firstname, Mode=TwoWay}"/>
                        </dataform:DataField>
                        <dataform:DataField Label="Last name">                         
                            <ComboBox x:Name="cb1" SelectedItem="{Binding Lastname, Mode=TwoWay}">
                                <ComboBoxItem Content="NameOne"></ComboBoxItem>
                                <ComboBoxItem Content="NameTwo"></ComboBoxItem>
                            </ComboBox>
                        </dataform:DataField>
                    </StackPanel>
                </DataTemplate>
            </dataform:DataForm.EditTemplate>
        </dataform:DataForm> 

MyCustomer对象包含Firstname和Lastname属性。

出于测试目的,我想通过组合框添加Lastname,但问题是,当我将Lastname属性绑定到组合框选定项时,保存到Lastname属性的值是字符串System.Windows。 Controls.ComboBoxItem而不是SelectedItem文本值。

如何将组合框中selectedItem的文本保存到Lastname属性?

2 个答案:

答案 0 :(得分:2)

试试这个

<ComboBox x:Name="cb1" SelectedValue="{Binding Lastname, Mode=TwoWay}" SelectedValuePath="Content">

答案 1 :(得分:0)

使用ComboBoxName.items.SelectedBoxItem

是SelectedBoxItem而不是SelectedItem