无法绑定视图模型属性-我自己的用户控件(WPF)



这个问题很有名,也很流行。。。

我今天经历了很多问题,但没有一个能解决我的问题,所以我决定向你寻求帮助。我想我遵循了其他用户的所有提示。。。

CustomControl.xaml

<UserControl x:Class="X.UserControls.CustomUserControl"
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"
x:Name="eqAction"
DataContext="{Binding RelativeSource={RelativeSource Self}}">
<StackPanel Orientation="Horizontal" VerticalAlignment="Center">
<TextBlock Text="{Binding Path=FirstName, RelativeSource={RelativeSource Mode=FindAncestor, AncestorType={x:Type UserControl}}, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}" />
</StackPanel>
</UserControl>

CustomControl.xaml.cs

public partial class CustomControl : UserControl
{
public static readonly DependencyProperty FirstNameProperty = DependencyProperty.Register(
"FirstName",
typeof(string),
typeof(CustomControl),
new FrameworkPropertyMetadata(default(string),
FrameworkPropertyMetadataOptions.BindsTwoWayByDefault));
public string FirstName
{
get
{
return (string)GetValue(FirstNameProperty);
}
set
{
SetValue(FirstNameProperty, value);
}
}
public CustomControl()
{
InitializeComponent();
}
}

MainViewModel.cs

private string _test;
public string Test
{
get { return _test; }
set
{
_test = value;
OnPropertyChanged(string.Empty);
}
}
public MainViewModel()
{
Test = "abc";
}
public new event PropertyChangedEventHandler PropertyChanged;
protected void OnPropertyChanged(string propertyName)
{
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
}

MainUserControl.xaml

<StackPanel x:Name="NotWorking">
<userControls:CustomControl FirstName="{Binding Path=Test, Mode=TwoWay}" />
</StackPanel>
<StackPanel x:Name="Working">
<userControls:CustomControl FirstName="My string value that works" />
</StackPanel>
<StackPanel x:Name="WorkingToo">
<TextBlock Text="{Binding Path=Test, Mode=TwoWay}" />
</StackPanel>
  • 在我的MainUserControl.xaml文件中,我有三个堆栈面板。首先是我想要实现的目标。遗憾的是,当前没有绑定任何数据(没有显示任何数据(。

  • 但是,如果不是绑定,而是为属性指定一个字符串值,则文本将正确显示(示例2(。

  • 示例3:当我创建到例如文本块组件的绑定时,文本也将显示。。。只有出现在第一个堆栈面板中的一个控件(名称NotWorking(的工作方式不同。。。

你看到错误了吗?

问题是在MainUserControl:中设置数据上下文的行

DataContext="{Binding RelativeSource={RelativeSource Self}}"

当您在代码中设置DataContext时,MainUserControl中的绑定将在CustomControl中而不是在MainViewModel中查找名为Test的属性。

最新更新