首页 文章

从UserControls [duplicate]更改Label的内容

提问于
浏览
-2

这个问题在这里已有答案:

我创建了一个名为 UserControl1 的UserControl并将其添加到我的 MainWindow 中 .

我想要的是,当用户点击UserControl上的 add 按钮时, MainWindow 中名为 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>

我怎样才能做到这一点 ?

1 回答

  • 1

    在userControl中定义一个属性说 NewData ,不要忘记实现 INotifyPropertyChanged Iterface .

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

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

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

    How to: Implement Property Change Notification

相关问题