在 UserControl 中设置数据绑定路径
我不知道如何根据参数
在UserControl
内设置Path
:
用户控件:
<UserControl x:Class="WpfApplication3.TestControl"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:diagnostics="clr-namespace:System.Diagnostics;assembly=WindowsBase">
<Grid>
<TextBox Text="{Binding Path=MyPath}"/>
</Grid>
</UserControl>
代码隐藏:
public partial class TestControl : UserControl
{
public string MyPath
{
get { return (string)GetValue(MyPathProperty); }
set { SetValue(MyPathProperty, value); }
}
public static readonly DependencyProperty MyPathProperty =
DependencyProperty.Register("MyPath", typeof(string), typeof(TestControl), new UIPropertyMetadata(""));
}
以及我打算如何使用it:
<local:TestControl MyPath="FirstName"></local:TestControl>
DataContext
将从父对象中获取,并包含一个User
类,其中包含一个FirstName
属性。
目标是拥有一个可以绑定到任何路径的用户控件。 我知道这一定非常简单,但我对该技术非常陌生,而且我找不到解决方案。
I don't konow how to set Path
inside a UserControl
based on a Parameter
:
User control:
<UserControl x:Class="WpfApplication3.TestControl"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:diagnostics="clr-namespace:System.Diagnostics;assembly=WindowsBase">
<Grid>
<TextBox Text="{Binding Path=MyPath}"/>
</Grid>
</UserControl>
Code behind:
public partial class TestControl : UserControl
{
public string MyPath
{
get { return (string)GetValue(MyPathProperty); }
set { SetValue(MyPathProperty, value); }
}
public static readonly DependencyProperty MyPathProperty =
DependencyProperty.Register("MyPath", typeof(string), typeof(TestControl), new UIPropertyMetadata(""));
}
And how I plan to use it:
<local:TestControl MyPath="FirstName"></local:TestControl>
DataContext
will be obtained from the parent object, and contains a class of User
with a FirstName
property inside.
The goal is to have a user control which can be bound to any path.
I know it must be super easy, but I'm very new to that technology and I couldn't find the resolution.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
我终于设法在代码中做到了这一点:
用户控件现在有一个没有绑定的文本框:
就是这样。
I've finally managed to do that, in code:
the user control now has a text box without binding:
and that's it.
当您在 XAML 中编写时:
这会尝试将您绑定到控件的 DataContext 的 MyPath 属性。
要绑定到控件自己的属性,我想你应该这样写:
Have one靠近备忘单,以防万一;)
When you write in your XAML:
this tries to bind you to the MyPath property of the DataContext of the control.
To bind to the control's own property, I guess you should write smth like:
Have one of the cheat sheets near, just in case ;)