【问题标题】:Why is two-way binding in silverlight not working?为什么silverlight中的双向绑定不起作用?
【发布时间】:2010-10-07 21:36:05
【问题描述】:

根据 Silverlight TwoWay 绑定的工作原理,当我更改 FirstName 字段中的数据时,它应该更改 CheckFirstName 字段中的值。

为什么不是这样?

答案:

谢谢杰夫,就是这样,其他人:这里是the full solution with downloadable code

XAML:

<StackPanel>
    <Grid x:Name="GridCustomerDetails">
        <Grid.RowDefinitions>
            <RowDefinition Height="Auto"/>
            <RowDefinition Height="Auto"/>
            <RowDefinition Height="*"/>
        </Grid.RowDefinitions>
        <Grid.ColumnDefinitions>
            <ColumnDefinition Width="Auto"/>
            <ColumnDefinition Width="300"/>
        </Grid.ColumnDefinitions>

        <TextBlock VerticalAlignment="Center" Margin="10" Grid.Row="0" Grid.Column="0">First Name:</TextBlock>
        <TextBox Margin="10" Grid.Row="0" Grid.Column="1" Text="{Binding FirstName, Mode=TwoWay}"/>

        <TextBlock VerticalAlignment="Center" Margin="10" Grid.Row="1" Grid.Column="0">Last Name:</TextBlock>
        <TextBox Margin="10" Grid.Row="1" Grid.Column="1" Text="{Binding LastName}"/>

        <TextBlock VerticalAlignment="Center" Margin="10" Grid.Row="2" Grid.Column="0">Address:</TextBlock>
        <TextBox Margin="10" Grid.Row="2" Grid.Column="1" Text="{Binding Address}"/>

    </Grid>

    <Border Background="Tan" Margin="10">
        <TextBlock x:Name="CheckFirstName"/>
    </Border>

</StackPanel>

后面的代码:

public Page()
{
    InitializeComponent();

    Customer customer = new Customer();
    customer.FirstName = "Jim";
    customer.LastName = "Taylor";
    customer.Address = "72384 South Northern Blvd.";

    GridCustomerDetails.DataContext = customer;

    Customer customerOutput = (Customer)GridCustomerDetails.DataContext;
    CheckFirstName.Text = customer.FirstName;

}

【问题讨论】:

    标签: silverlight data-binding two-way-binding


    【解决方案1】:

    您的Customer 类型必须支持INotifyPropertyChanged,以便绑定知道您的FirstName 属性值何时更改。

    这个tutorial 可以帮助您让您的代码正常工作。

    【讨论】:

    • 您也可以从DependencyObject 派生并将FirstName 设为依赖属性。 Jeff 的解决方案更合适,但您有两种选择。
    • @carlmon:好点子,这是实现此功能的另一种方法。
    【解决方案2】:

    解决方案是对CheckFirstName使用元素绑定

    【讨论】:

      【解决方案3】:

      Grid 容器中的控件不知道 FirstName、LastName 和 Address 是什么。我认为您需要将网格绑定到代码隐藏中的对象:

      <Grid x:Name="GridCustomerDetails" DataContext="Customer"> 
      

      现在,该容器内的每个控件都可以绑定到 Customer 的属性。你像这样绑定它:

      <TextBox Margin="10" Grid.Row="0" Grid.Column="1" 
               Text="{Binding Path=FirstName, Mode=TwoWay}"/>   
      

      在您的代码中,确保“客户”是一个类对象,并且是公开声明的。

      如果这不起作用,请尝试在顶部的页面声明和命名空间中添加 x:Name=""。

      我希望这会有所帮助!

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2012-08-20
        • 2017-03-23
        • 1970-01-01
        • 2018-08-14
        • 2012-02-14
        相关资源
        最近更新 更多