Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/329.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 从用户控件更改标签的内容_C#_Wpf_Data Binding_User Controls_Window - Fatal编程技术网

C# 从用户控件更改标签的内容

C# 从用户控件更改标签的内容,c#,wpf,data-binding,user-controls,window,C#,Wpf,Data Binding,User Controls,Window,我创建了一个名为UserControl1的用户控件,并将其添加到我的主窗口中 我想要的是,当用户单击用户控件上的add按钮时,主窗口中名为data的标签的内容会发生更改 <UserControl x:Class="WpfApplication6.UserControl1" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://sc

我创建了一个名为
UserControl1
的用户控件,并将其添加到我的主窗口中

我想要的是,当用户单击用户控件上的
add
按钮时,主窗口中名为
data
的标签的内容会发生更改

<UserControl x:Class="WpfApplication6.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="300" d:DesignWidth="300">
    <Grid>
        <Button Content="add" x:Name="add"/>
    </Grid>
</UserControl>

<Window x:Class="WpfApplication6.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" 
        xmlns:WpfApplication6="clr-namespace:WpfApplication6"
        Title="MainWindow" Height="350" Width="525">
    <Grid>
        <StackPanel Orientation="Vertical">
            <Label Content="data" x:Name="data"/>
            <WpfApplication6:UserControl1 x:Name="myUC"/>
    </StackPanel>
    </Grid>
</Window>


如何执行此操作?

在用户控件中定义一个属性,比如说
NewData
,不要忘记实现
INotifyPropertyChanged
Iterface

将标签内容绑定到userControl.NewData属性:

<Label Content="{Binding ElementName=myUC, Path=NewData" x:Name="data"/>

当按下userControl的按钮时,将所需数据设置为NewData属性


您可以将标签内容绑定到userControl属性。当按下“添加”按钮时,userControl将设置属性,标签将更改I尝试的ICommand、DependencyProperty、。。。什么都没用。因此,我创建了一个新项目,现在我请求您提供帮助(我需要一些代码示例)以及为什么投票否决我的问题?您是否考虑过MVVM模式?@Wassim您在第一次提出问题时就得到了一个很好(且正确)的答案。此外,您可以随时编辑问题以添加其他信息。如何实现INotifyPropertyChanged?您的类应继承INotifyPropertyChanged接口,然后在属性的
Setter
中调用PropertyChanged事件<代码>PropertyChanged(这是新的PropertyChangedEventArgs(“新数据”)