【问题标题】:Change the content of a Label from a UserControls [duplicate]从 UserControls 更改标签的内容 [重复]
【发布时间】:2012-09-13 15:37:48
【问题描述】:

我创建了一个名为 UserControl1 的用户控件并将其添加到我的 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>

我该怎么做?

【问题讨论】:

  • 您可以将标签内容绑定到 userControl 属性。当按下添加按钮时,userControl 将设置属性和标签将改变
  • 我尝试了 ICommand、DependencyProperty 等,但没有任何效果。所以我创建了一个新项目,现在我请你帮忙(我想要一些代码示例)
  • 为什么要否决我的问题?
  • 你考虑过 MVVM 模式吗?
  • @Wassim 第一次提出问题时,您的问题得到了很好的(而且正确的)答案。此外,您可以随时编辑您的问题以添加更多信息。

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


【解决方案1】:

在userControl中定义一个属性NewData,别忘了实现INotifyPropertyChangedIterface。

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

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

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

How to: Implement Property Change Notification

【讨论】:

  • 如何实现 INotifyPropertyChanged ?
  • 你的类应该继承 INotifyPropertyChanged 接口,然后在属性的Setter 中调用 PropertyChanged 事件。 PropertyChanged(this, new PropertyChangedEventArgs("NewData"));
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-06-14
  • 2011-10-29
  • 2019-02-04
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多