【问题标题】:Why does binding to elementName in usercontrol work even though Name is changed by user of usercontrol?为什么即使名称由用户控件的用户更改,绑定到用户控件中的元素名称仍然有效?
【发布时间】:2020-01-14 03:12:54
【问题描述】:

我有以下非常简单的 WPF 应用程序:

用户控件: XAML:

<UserControl x:Class="WPFUserControlTest.TestControl"
         xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
         xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
         xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" 
         xmlns:d="http://schemas.microsoft.com/expression/blend/2008" 
         xmlns:local="clr-namespace:WPFUserControlTest"
         mc:Ignorable="d" 
         d:DesignHeight="450" d:DesignWidth="800"
         x:Name="root">
<Grid>
    <TextBlock Text="{Binding ElementName=root, Path=InputString}"/>
</Grid>

代码背后:

namespace WPFUserControlTest
{
    public partial class TestControl : UserControl
    {
        public TestControl()
        {
            InitializeComponent();
        }

        public string InputString
        {
            get { return (string)GetValue(InputStringProperty); }
            set { SetValue(InputStringProperty, value); }
        }

        public static readonly DependencyProperty InputStringProperty =
            DependencyProperty.Register("InputString", typeof(string), typeof(TestControl), new PropertyMetadata(""));
    }
}

我的主窗口:

<Window x:Class="WPFUserControlTest.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"
        xmlns:local="clr-namespace:WPFUserControlTest"
        mc:Ignorable="d"
        Title="MainWindow" Height="450" Width="800">
    <Grid>
        <StackPanel>
        <local:TestControl x:Name="Mercedes" InputString="Mercedes"/>
        <local:TestControl InputString="Volvo"/>
        </StackPanel>
    </Grid>
</Window>

我想知道的是,即使主窗口更改了控件的名称,使用 ElementName 的用户控件内部的绑定似乎也能正常工作。 这个绑定是在编译时以某种方式在控件内部完成的吗?

当我在 Live Visual Tree 中查看它时,我看到我的一个控件实例的名称为“root”,而一个名为“mercedes”。他们仍然按预期工作......

【问题讨论】:

  • 替代绑定:&lt;TextBlock Text="{Binding InputString, RelativeSource={RelativeSource AncestorType=UserControl}}"/&gt;。它避免了对x:Name="root" 和相关生成字段的需要。

标签: c# wpf xaml binding


【解决方案1】:

您应该阅读XAML namescopes。名称“Mercedes”仅适用于窗口的名称范围,“root”适用于UserControl 的名称范围。

该窗口不能将UserControl 称为“根”,因为它不属于同一个名称范围。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-10-31
    • 2021-11-30
    相关资源
    最近更新 更多