【发布时间】:2018-10-22 19:40:12
【问题描述】:
我已尽我所能简化代码以尝试获得一段有效的代码,但我仍然做不到。一些建议将不胜感激。
我正在尝试让 DependencyProperty 工作,就这么简单,但我在主窗口中设置的数据没有显示在用户控件中。
在 MainWindow 中,我将 xaml 中的 TextValue 设置为“hi”。 TextValue 在 xaml 中显示并编译得很好,所以我很确定我的 DependencyProperty 设置正确。对话框完全打开后,我查看调试器,我的属性 TextValue 仍然为空。
我是否缺少设置数据上下文?也许我在我想做的事情上偏离了基础。
感谢您花时间找出我做错了什么。
我的用户控件是:UserControl1 Xaml:
<UserControl x:Class="WpfApplication1.UserControl1"
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"
Loaded="UserControl_Loaded"
mc:Ignorable="d"
d:DesignHeight="300" d:DesignWidth="300">
<Grid>
</Grid>
</UserControl>
UserControl1.xaml.cs 是:
namespace WpfApplication1
{
/// <summary>
/// Interaction logic for UserControl1.xaml
/// </summary>
public partial class UserControl1 : UserControl
{
public UserControl1()
{
InitializeComponent();
}
public static readonly DependencyProperty TextProperty = DependencyProperty.Register("TextValue", typeof(string), typeof(UserControl1));
private string _tv;
public string TextValue
{
get
{
return _tv;
}
set
{
_tv = value;
}
}
private void UserControl_Loaded(object sender, RoutedEventArgs e)
{
}
}
}
我的调用窗口 xaml 是:
<Window x:Class="WpfApplication1.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:usercontrols="clr-namespace:WpfApplication1"
Title="MainWindow" Height="350" Width="525"
Loaded='Window_Loaded'>
<Grid>
<usercontrols:UserControl1 x:Name="usercontroltest1" TextValue="hi"/>
</Grid>
</Window>
我的调用窗口.cs是:
namespace WpfApplication1
{
/// <summary>
/// Interaction logic for MainWindow.xaml
/// </summary>
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
}
private void Window_Loaded(object sender, RoutedEventArgs e)
{
}
}
}
【问题讨论】:
标签: wpf user-controls dependency-properties