我有一个:
System.Windows.Data 错误:4:找不到与引用“ElementName = Test”进行绑定的源。绑定表达式:路径=值;数据项=空;目标元素是 'Slider' (Name=''); 目标属性是“值”(类型“双”)
在非常特殊的情况下出错。我虽然关于名称范围问题,但我不知道如何解决它。
考虑以下 WPF 应用程序:
MyUserControl.xaml:
<UserControl x:Class="WpfApplication1.MyUserControl"
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" mc:Ignorable="d"
d:DesignHeight="300" d:DesignWidth="300">
<Grid>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="Auto" />
<ColumnDefinition Width="*" />
</Grid.ColumnDefinitions>
<Grid.RowDefinitions>
<RowDefinition Height="Auto" />
<RowDefinition Height="Auto" />
</Grid.RowDefinitions>
<Label Grid.Row="0" Content="Move me !"/>
<Slider x:Name="Test" Grid.Row="0" Grid.Column="1" />
<Label Grid.Row="1" Content="Binded slider"/>
<ContentPresenter Grid.Row="1" Grid.Column="1">
<ContentPresenter.Content>
<Slider Value="{Binding Value, ElementName=Test}"/>
</ContentPresenter.Content>
</ContentPresenter>
</Grid>
</UserControl>
MyUserControl.xaml.cs:
using System.Windows.Controls;
namespace WpfApplication1
{
public partial class MyUserControl : UserControl
{
public MyUserControl()
{
InitializeComponent();
}
}
}
MainWindow.xaml:
<Window x:Class="WpfApplication1.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" Title="MainWindow" Width="300" Height="120">
<StackPanel>
<Button Click="Button_Click" Content="Click me to show Sliders !" Height="25"/>
<ContentPresenter x:Name="contentPresenter"/>
</StackPanel>
</Window>
MainWindow.xaml.cs:
using System.Windows;
namespace WpfApplication1
{
public partial class MainWindow : Window
{
private MyUserControl myUserControl;
public MainWindow()
{
InitializeComponent();
myUserControl = new MyUserControl();
}
private void Button_Click(object sender, RoutedEventArgs e)
{
contentPresenter.Content = myUserControl;
}
}
}
给定 MyUserControl.xaml 的代码,我希望绑定的滑块与第一个滑块具有相同的值。
但什么也没有发生。
现在,棘手的部分:启动应用程序,单击按钮,移动第一个滑块,打开“WPF Inspector”并将其附加到应用程序。结果:绑定已修复。
你如何解释这种现象?