c# - 使用用户控件时的 WPF 数据绑定(bind)

标签 c# wpf mvvm

我是 WPF 和 MVVM 模式的新手,我正在尝试制作一个使用多个控件的应用程序,因此我分别创建每个控件,并且在如何在控件之间共享数据方面遇到了一些困难

假设我有一个带有标签的控件和另一个包含文本框的控件,
在我想要的主窗口中,当我添加两个自定义控件时,我需要标签控件来显示我在文本框中输入的内容,如果我直接在窗口中使用标签和文本框,我知道如何实现它,但我需要为了解决类似的问题,
这是标签控件

<UserControl x:Class="TestWPF2.Views.LabelControl"
             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>
        <Label ></Label>
    </Grid>
</UserControl>

文本框自定义控件
<UserControl x:Class="TestWPF2.Views.TextBoxControl"
             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>
        <TextBox ></TextBox>
    </Grid>
</UserControl>

这是窗口代码
<Window x:Class="TestWPF2.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:V="clr-namespace:TestWPF2.Views"
        xmlns:Controls="clr-namespace:TestWPF2.Views"
        Title="MainWindow" Height="350" Width="525">
    <DockPanel LastChildFill="True">

        <Controls:TextBoxControl   ></Controls:TextBoxControl>
        <Controls:LabelControl   ></Controls:LabelControl>
    </DockPanel>
</Window>

最佳答案

通过绑定(bind),控件将继承其父级的数据上下文。

如果您将窗口数据上下文设置为“模型”(如果您需要限制它,则将控件数据上下文设置为“模型”)并且该模型具有名为“SomeText”的属性,您可以绑定(bind)文本框和标签,如下所示:

<TextBox BorderBrush="Black" Text="{Binding Path=Model.SomeText,UpdateSourceTrigger=PropertyChanged}" />

如果您需要更多信息,请告诉我。绑定(bind)是一开始的野兽。

您不需要任何代码来连接控件。

关于c# - 使用用户控件时的 WPF 数据绑定(bind),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21260276/

相关文章:

c# - EF Core 2.1 中的动态数据播种迁移生成取决于在 OnModelCreating() 中使用的 DbContext bool-flag

c# - svn 和 c#/visual studio 有什么限制吗?

IsEnabled 上的 WPF 按钮样式背景图像交换

c# - 我在 WPF 中的哪里放置我的登录逻辑以及如何在 MVVM 中处理它?

WPF MVVM : Convention over Configuration for ResourceDictionary?

c# - c#中的基频+语音检测

c# - 如何在 StructureMap 中使用 InstanceScope.HttpSession?

c# - 如何在 WPF 中仅在左侧和右侧指定矩形描边?

wpf - 有没有一种简单的方法来指定路径为 "level"向上的 WPF 数据绑定(bind)?

ios - ReactiveCocoa 与 MVVM