【发布时间】:2014-02-20 08:41:31
【问题描述】:
在使用用户控件和数据绑定时有一个问题困扰着我。 我想知道为什么这不起作用,以及如何使它起作用。
我创建了一个最小的示例(我没有费心创建视图模型):
首先,有一个包含文本框和按钮的用户控件。
<UserControl x:Class="DatabindingProblem.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="23" d:DesignWidth="300">
<StackPanel Orientation="Horizontal">
<TextBox Text="{Binding Path}" Width="250"></TextBox>
<Button Click="Button_Click" Width="50">click</Button>
</StackPanel>
</UserControl>
后面的代码(一个依赖属性“路径”):
namespace DatabindingProblem
{
public partial class UserControl1 : UserControl
{
public UserControl1()
{
InitializeComponent();
}
public string Path
{
get { return (string)GetValue(PathProperty); }
set { SetValue(PathProperty, value); }
}
public static readonly DependencyProperty PathProperty =
DependencyProperty.Register("Path", typeof(string), typeof(UserControl1), new PropertyMetadata(""));
private void Button_Click(object sender, RoutedEventArgs e)
{
Path = "test";
}
}
}
窗口:
<Window x:Class="DatabindingProblem.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="clr-namespace:DatabindingProblem"
Title="MainWindow" Height="350" Width="525">
<Grid>
<local:UserControl1 Height="23" Path="{Binding FilePath}" />
</Grid>
</Window>
windows 代码隐藏(依赖属性 FilePath):
namespace DatabindingProblem
{
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
}
public string FilePath
{
get { return (string)GetValue(FilePathProperty); }
set { SetValue(FilePathProperty, value); }
}
public static readonly DependencyProperty FilePathProperty =
DependencyProperty.Register("FilePath", typeof(string), typeof(MainWindow), new PropertyMetadata(""));
}
}
我想知道为什么“测试”在文本框中不可见,并且在单击按钮后不会传播到窗口中的“文件路径”。
谁能给我解释一下?
谢谢
【问题讨论】:
标签: wpf data-binding dependency-properties assign