WPF多绑定相对源FindAncestor评估性能

3
在以下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(以及其路径)没有被更改,它会仅搜索一次吗?还是每次多重绑定中的任何属性更改时都会搜索祖先?假设每个属性都有变更通知。

1个回答

4
我认为唯一可能的测试方法是实际移除控件以查看它是否找到了正确的控件。
通过这种方式进行测试,无论使用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";
    }
}

首次运行时,您将看到:

enter image description here

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

enter image description here


谢谢,确实只评估一次! - Yoghurt

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接