我在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>
Run Code Online (Sandbox Code Playgroud)
后面的代码有一个名为"FirstMessage"的参数,它被设置为我的用户控件TextBlock的文本:
public partial class GetLatest : UserControl
{
public string FirstMessage { get; set; }
public GetLatest()
{
InitializeComponent();
theTextBlock.Text = this.FirstMessage;
}
}
Run Code Online (Sandbox Code Playgroud)
在我的主代码中,我可以使用intellisense在我的用户控件中设置FirstMessage参数:
<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>
Run Code Online (Sandbox Code Playgroud)
但是,它仍然没有设置文本.我已经尝试了Text ="{Binding Path = FirstMessage}"以及我找到的其他语法,但没有任何效果.
如何在用户控件中访问FirstMessage值?
Szy*_*zga 16
您的绑定方法不起作用,因为您的属性FirstMessage在更新时不会通知.使用依赖属性.见下文:
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;
}
}
Run Code Online (Sandbox Code Playgroud)
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>
Run Code Online (Sandbox Code Playgroud)
每当FirstMessage属性更改时,您的文本块将自行更新.
| 归档时间: |
|
| 查看次数: |
13188 次 |
| 最近记录: |