0

こんにちは、MVVM Silverlight アプリに取り組んでおり、TextBox の UpdateSourceTrigger プロパティを使用して、実行時にバインディング式を次のように更新します。

.xaml.cs:

BindingExpression beID = txtEmpID.GetBindingExpression(TextBox.TextProperty); beID.UpdateSource();

BindingExpression beAge = txtAge.GetBindingExpression(TextBox.TextProperty); beAge.UpdateSource();

.xaml:

<Grid x:Name="LayoutRoot"
      Background="White" 
      DataContext="{Binding Source={StaticResource keyEMPVM},    
      UpdateSourceTrigger=Explicit}">

    //<Grid.RowDefinitions>

    //<Grid.ColumnDefinitions>

    <sdk:Label Grid.Row="2"
               Grid.Column="1"
               Target="{Binding ElementName=txtEmpID}" />
    <TextBox x:Name="txtEmpID"
             Grid.Row="2"
             Grid.Column="2"
             Style="{StaticResource ContentTextBoxStyle}"
             Text="{Binding emp.ID, Mode=TwoWay, ValidatesOnExceptions=True,
                                    ValidatesOnDataErrors=True,  NotifyOnValidationError=True, UpdateSourceTrigger=Explicit}" />

    <sdk:Label Grid.Row="4"
               Grid.Column="1"
               Target="{Binding ElementName=txtAge}" />
    <TextBox x:Name="txtAge"
             Grid.Row="4"
             Grid.Column="2"
             Style="{StaticResource ContentTextBoxStyle}"
             Text="{Binding emp.Age, Mode=TwoWay, ValidatesOnExceptions=True,
                                    ValidatesOnDataErrors=True, NotifyOnValidationError=True, UpdateSourceTrigger=Explicit}" />

    <Button x:Name="btnSubmit"
            Grid.Row="6"
            Grid.Column="1"
            Grid.ColumnSpan="2"
            Style="{StaticResource ContentButtonStyle}"
            Content="Submit"
            Command="{Binding Path=UpdateEmployee}"
            CommandParameter="{Binding emp.ID}" />

この場合、テキスト ボックスごとに手動でバインディング式を実行しています。単一のインスタンスで、グリッド内のすべてのテキスト ボックス コントロールに対してこのバインディング式を実行できる方法はありますか。

4

1 に答える 1

0

グリッド内のそれぞれ を更新する場合TextBoxは、次のコードを使用できます。

    private void LayoutRoot_KeyDown(object sender, KeyEventArgs e)
    {
        var grid = (Grid)sender;
        foreach (var tb in GetChildren<TextBox>(grid))
        {
            var be = tb.GetBindingExpression(TextBox.TextProperty);
            if(be != null) be.UpdateSource();
        }
    }

    public IEnumerable<T> GetChildren<T>(DependencyObject d) where T:DependencyObject
    {
        var count = VisualTreeHelper.GetChildrenCount(d);
        for(int i = 0; i < count; i++)
        {
            var c = VisualTreeHelper.GetChild(d, i);
            if (c is T)
                yield return (T)c;

            foreach (var c1 in GetChildren<T>(c))
                yield return c1;
        }
    }

KeyDown イベントは単なる例です。おそらく再帰は問題を解決する最良の方法ではありませんが、最も簡単な方法です

于 2011-02-21T21:36:46.347 に答える