我想访问MainWindowViewModel
中MyUserControlViewModel
属性的属性我就像这样绑定它。
我有一个UserControl
,其中包含一个textbox
,我希望公开此text
的{{1}}属性,因此我添加了名为“SearchText”的依赖项属性即可。我的用户控件有自己的视图模型,其属性名称为textbox
。我想将此属性绑定到commentText
的{{1}}属性
我有主窗口,我正在使用此用户控件。 MainWindow视图模型具有名为Text
的属性,我想与我的用户控件的textBox
绑定。
MyUserControl.xaml
Comment
这里我想将Text属性绑定到其视图的CommentText属性 模型
MyUserControl.xaml.cs
SearchText
MyUserControlViewModel.cs
<TextBox Text="{Binding RelativeSource={RelativeSource AncestorType={x:Type local:MyUserControl}}, Path=SearchText}"/>
MainWindow.xaml
/// <summary>
/// DependencyProperty for SearchText
/// </summary>
public static readonly DependencyProperty SearchTextProperty =
DependencyProperty.Register(
"SearchText",
typeof(string),
typeof(MyUserControl),
new FrameworkPropertyMetadata(string.Empty,
FrameworkPropertyMetadataOptions.BindsTwoWayByDefault,
new PropertyChangedCallback(SearchTextCallBack)));
/// <summary>
/// Initializes a new instance of the <see cref="MyUserControl"/> class.
/// </summary>
public MyUserControl()
{
InitializeComponent();
}
/// <summary>
/// Gets or sets the Search Text.
/// </summary>
/// <value> The Search Text. </value>
public string SearchText
{
get { return GetValue(SearchTextProperty) as string; }
set
{
SetValue(SearchTextProperty, value);
}
}
/// <summary>
/// Search Text call back.
/// </summary>
/// <param name="property"> The property. </param>
/// <param name="args">
/// The <see cref="System.Windows.DependencyPropertyChangedEventArgs" /> instance containing
/// the event data.
/// </param>
public static void SearchTextCallBack(DependencyObject property, DependencyPropertyChangedEventArgs args)
{
var myUserControl= property as MyUserControl;
if (args.NewValue == null)
{
return;
}
if (myUserControl!= null)
{
myUserControl.SearchText = args.NewValue.ToString();
}
}
MainWindowViewModel.cs
public string CommentText
{
get
{
return _commentText;
}
set
{
_commentText = value;
}
}