简体   繁体   English

在WPF中的2个用户控件之间共享数据

[英]Sharing data between 2 usercontrols in WPF

I have usercontrol lets say UA with a textbox in it. 我有usercontrol可以说带有文本框的UA。 Now i want to access the value in the textbox in the codebehind of another usercontrol, let says UB Both the usercontrols are on a tab. 现在,我想访问另一个用户控件背后代码中的文本框中的值,让我们说UB。两个用户控件都在选项卡上。 What is the efficient way to do this? 有效的方法是什么?

Provide both UserControls with a dependency property that the other can bind to or 为两个UserControls提供一个依赖属性,另一个可以绑定到该依赖属性或

Some xaml: 一些xaml:

<local:Uc1 x:Name="uc1" DataContext="{Binding ElementName=uc2, Path=Thing}" />
<local:Uc2 x:Name="uc2" />

This can be done in code as well. 这也可以用代码来完成。

or bind both UserControls to the same ViewModel. 或将两个UserControl绑定到同一ViewModel。

also look this and this 也期待这个这个

Updated Answer 更新的答案

Defining custom Dependency Property in MainWindow.cs 在MainWindow.cs中定义自定义Dependency属性

public string Prop
    {
        get { return (string)GetValue(PropProperty); }
        set { SetValue(PropProperty, value); }
    }

    // Using a DependencyProperty as the backing store for Prop.  This enables animation, styling, binding, etc...
    public static readonly DependencyProperty PropProperty =
        DependencyProperty.Register("Prop", typeof(string), typeof(MainWindow), new PropertyMetadata("Hello!!"));

Now just bind this dp to your two user control UserControl 1 现在,只需将此dp绑定到您的两个用户控件UserControl 1

 <Grid>
    <TextBox Height="25" Text="{Binding RelativeSource={RelativeSource AncestorType=Window},Path=Prop, 
        Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}" Width="65"/>
</Grid>

UserControl 2 用户控件2

 <Grid>
    <TextBox Height="25" Text="{Binding RelativeSource={RelativeSource AncestorType=Window},Path=Prop, 
        Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}" Width="65"/>
</Grid>

This is just an example to get going with custom dp`s. 这只是开始使用自定义dp的示例。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM