问题描述
我在 WPF 中创建了一个用户控件:
I created a user control in WPF:
<UserControl x:Class="TestUserControl.Controls.GetLatest"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">
<TextBlock Name="theTextBlock"/>
</UserControl>
后面的代码有一个名为FirstMessage"的参数,它设置为我的用户控件 TextBlock 的文本:
The code behind has a parameter called "FirstMessage" which it sets as the text of my user control TextBlock:
public partial class GetLatest : UserControl
{
public string FirstMessage { get; set; }
public GetLatest()
{
InitializeComponent();
theTextBlock.Text = this.FirstMessage;
}
}
在我的主代码中,我可以使用智能感知在我的用户控件中设置 FirstMessage 参数:
In my main code I can set the FirstMessage parameter in my user control with intellisense:
<Window x:Class="TestUserControl.Window1"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="Window1" Height="300" Width="300"
xmlns:controls="clr-namespace:TestUserControl.Controls"
>
<StackPanel>
<controls:GetLatest FirstMessage="This is the title"/>
</StackPanel>
</Window>
但是,它仍然没有设置文本.我已经尝试过 Text="{Binding Path=FirstMessage}" 和我发现的其他语法,但没有任何效果.
However, it still doesn't set the text. I've tried Text="{Binding Path=FirstMessage}" and other syntaxes I have found but nothing works.
如何访问用户控件中的 FirstMessage 值?
How can I access the FirstMessage value in my user control?
推荐答案
您的绑定方法不起作用,因为您的属性 FirstMessage 在更新时没有通知.为此使用依赖属性.见下文:
Your approach to binding doesn't work because your property FirstMessage doesn't notify when it gets updated. Use Dependency Properties for that. See below:
public partial class GetLatest : UserControl
{
public static readonly DependencyProperty FirstMessageProperty = DependencyProperty.Register("FirstMessage", typeof(string), typeof(GetLatest));
public string FirstMessage
{
get { return (string)GetValue(FirstMessageProperty); }
set { SetValue(FirstMessageProperty, value); }
}
public GetLatest()
{
InitializeComponent();
this.DataContext = this;
}
}
XAML:
<UserControl x:Class="TestUserControl.Controls.GetLatest"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">
<TextBlock Text="{Binding FirstMessage}" />
</UserControl>
每当 FirstMessage 属性发生变化时,您的文本块都会自行更新.
Whenever the FirstMessage property changes, your text block will update itself.
这篇关于如何读取 WPF UserControl 中传递的参数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!