这必须很简单,至少在旧的 .Net 中它可能需要四行代码。我在 VS2010、C#、WPF4 中工作。
我有一个带有文本框的用户控件。当我单击主窗口中的按钮时,我希望我的用户控件文本框反映一些文本。这在 WPF4 中是否可以使用少于 500 行深奥的代码?
问题是,虽然我知道文本框正在获取用户控制代码中的断点所证明的新文本,但该文本永远不会反映到主窗口。主窗口仍然显示原始文本。它必须是某种绑定的东西,我真的不认为我应该为这种简单的情况创建模板和资源等等。我在 WPF4 的森林中忘记了一些简单的事情。下面是我所拥有的。点击按钮后,文本框还是空白;它没有说“你好地球人”。
在用户控制代码中:
public partial class UserControl1 : UserControl
{
public static readonly DependencyProperty TextProperty;
public UserControl1()
{
InitializeComponent();
}
static UserControl1()
{
TextProperty = DependencyProperty.Register("Text", typeof(string), typeof(UserControl1), new UIPropertyMetadata(null));
}
public string Text
{
get { return (string)GetValue(TextProperty); }
set { SetValue(TextProperty, value); }
}
}
用户控件 xaml:
<UserControl x:Class="WTFUserControlLibrary.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">
<Grid Height="164" Width="220">
<TextBox Name="txtTest" BorderBrush="red" BorderThickness="2" Height="25" Text="{Binding ElementName=UserControl1, Path=Text, Mode=TwoWay}"></TextBox>
</Grid>
(我不知道在这种情况下文本绑定应该做什么。)
主窗口代码:
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
}
private void button1_Click(object sender, RoutedEventArgs e)
{
WTFUserControlLibrary.UserControl1 uc = new WTFUserControlLibrary.UserControl1();
uc.Text = "hello earthlings";
}
}
和主窗口 xaml:
<Window x:Class="WpfApplication2.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:my="clr-namespace:WTFUserControlLibrary;assembly=WTFUserControlLibrary"
Title="MainWindow" Height="350" Width="525">
<Grid>
<Button Content="Button" Height="23" HorizontalAlignment="Left" Margin="71,65,0,0" Name="button1" VerticalAlignment="Top" Width="75" Click="button1_Click" />
<my:UserControl1 HorizontalAlignment="Left" Margin="71,94,0,0" Name="userControl11" VerticalAlignment="Top" Height="116" Width="244" />
</Grid>
感谢地球人(还有那些设计这个烂摊子的人!)