【发布时间】:2014-01-21 14:00:08
【问题描述】:
我是 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>
TextBox 自定义控件
<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>
【问题讨论】:
-
顺便说一句,您不应该创建
UserControl只是为了包装单个控件,例如Label或TextBox;只需直接实例化Label或TextBox。我不知道您的实际代码是否这样做,或者这只是一个简化的示例。 -
看看Simple Pattern for Creating Re-useable UserControls,以正确的方式进行操作。
-
您可能应该在问题中包含“代码背后”