我想创建一个用户控件,它本质上是一个带有文本框的标签。现在我希望能够绑定TextBox.Text
到不同的值。
为此,我在我的 UserControl 中创建了一个 DependencyProperty,现在正尝试将某些内容绑定到新创建的 DependencyProperty,但文本似乎没有得到更新。
我的 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"
mc:Ignorable="d"
d:DesignHeight="48" d:DesignWidth="200">
<Grid>
<WrapPanel Height="48" HorizontalAlignment="Left" Name="wrapPanel1" VerticalAlignment="Top" Width="200">
<Label Content="Label" Height="48" Name="label1" Width="100" />
<TextBox Height="48" Name="textBox1" Width="100" />
</WrapPanel>
</Grid>
我的 UserControl1.xaml.cs 看起来像这样:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using System.Diagnostics;
namespace WpfApplication1
{
/// <summary>
/// Interaction logic for UserControl1.xaml
/// </summary>
public partial class UserControl1 : UserControl
{
private string value;
public string Value
{
get { return value; }
set
{
this.value = value;
textBox1.Text = value;
Trace.TraceInformation("value set in UserControl1");
}
}
public static readonly DependencyProperty ValueProperty =
DependencyProperty.Register("Value", typeof(string), typeof(UserControl1));
public UserControl1()
{
InitializeComponent();
}
}
}
我正在使用这样的 UserControl:
<my:UserControl1 x:Name="userControl11" Value="{Binding Path=Name}" />
withDataContext
设置为具有 Name 属性并为此属性实现 INotifyPropertyChanged 的对象。