从UserControls更改Label的内容

时间:2012-09-13 15:37:49

标签: c# wpf data-binding user-controls window

我创建了一个名为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 个答案:

答案 0 :(得分: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