2

在以下 MultiBinding 表达式的情况下,如果 PropB 多次更改,绑定引擎将搜索 DataGrid 祖先多少次?

<MultiBinding Converter="{StaticResource TestConverter}"> 
    <Binding Path="PropA"/> 
    <Binding Path="PropB" /> 
    <Binding Path="DataContext.Sub.PropertyC" RelativeSource="{RelativeSource Mode=FindAncestor,AncestorType=DataGrid}" /> 
</MultiBinding>

如果 PropertyC(和它的路径)从未改变,它会只搜索一次吗?还是会在每次更改多重绑定中的属性之一时搜索祖先?假设每个属性都有更改通知。

4

1 回答 1

4

我认为可以测试这一点的唯一方法是实际删除控件以查看它是否找到正确的控件。

以这种方式测试它,无论是否使用 a ,它看起来都只评估一次MultiBinding

<Window x:Class="RelativeTest.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"
        mc:Ignorable="d"
        Title="MainWindow" Height="350" Width="525">
    <StackPanel x:Name="Stack">
        <TextBlock x:Name="TB1" Text="Foo" />
        <TextBlock x:Name="TB2" Text="Bar" />

        <Border BorderThickness="1" BorderBrush="Black" />

        <TextBlock Text="{Binding RelativeSource={RelativeSource Mode=FindAncestor, AncestorType=StackPanel}, Path=Children[0].Text}" 
                   Foreground="Red" />

        <TextBlock Foreground="Blue">
            <TextBlock.Text>
                <MultiBinding StringFormat="{}{2}">
                    <Binding ElementName="TB1" Path="Text" />
                    <Binding ElementName="TB2" Path="Text" />
                    <Binding RelativeSource="{RelativeSource Mode=FindAncestor, AncestorType=StackPanel}" Path="Children[0].Text" />
                </MultiBinding>
            </TextBlock.Text>
        </TextBlock>
        <Button Click="ButtonBase_OnClick" Content="Remove 1st Child" />
    </StackPanel>
</Window>

public partial class MainWindow : Window
{
    public MainWindow()
    {
        InitializeComponent();
    }

    void ButtonBase_OnClick(object sender, RoutedEventArgs e)
    {
        Stack.Children.Remove(Stack.Children[0]);
        TB1.Text = "You'll see me if I am looked up once.";
        TB2.Text = "You'll see me twice if I am re-evaulated each time";
    }
}

最初运行它时,您将看到:

在此处输入图像描述

单击按钮时,它将删除第一个子项并更改 TextBlocks 以显示较新的文本以指示它现在绑定到哪个子项。

在此处输入图像描述

于 2017-08-28T22:37:50.983 回答