【发布时间】:2013-11-27 23:07:18
【问题描述】:
我刚开始使用 WPF,已经使用 WinForms 一段时间了,但似乎在第一关就掉了下来。
我的主要 XAML 定义为
<Window x:Class="FHIRCDALoader.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="clr-namespace:FHIRCDALoader.xaml"
Title="FHIR CDA Loader" Height="350" Width="525"
Icon="Icons/color_swatch.png">
<Window.CommandBindings>
<CommandBinding Command="ApplicationCommands.New"
Executed="NewDocument" />
</Window.CommandBindings>
<DockPanel>
<local:menubar DockPanel.Dock="Top"/>
<local:toolbar DockPanel.Dock="Top"/>
<local:statusbar DockPanel.Dock="Bottom" />
<RichTextBox x:Name="Body"/>
</DockPanel>
</Window>
注意用户控件的使用,其中之一是“状态栏”
<UserControl x:Class="FHIRCDALoader.xaml.statusbar"
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">
<StatusBar >
<StatusBarItem>
<TextBlock x:Name="bbstatusbar" />
</StatusBarItem>
</StatusBar>
</UserControl>
所以在 MainWindow.xaml.cs 中,我看到我可以从主 XAML 文件中引用 RichTextBox 命名主体。但是,我无法在名为“bbstatusbar”的 UserControl 中引用 TextBlock。
如何从 MainWindow.xaml.cs 中设置 TextBlock 的值?
【问题讨论】:
-
通常首选的方法是使用 MVVM:(1) 为主窗口和控件定义视图模型,(2) 将文本框文本的值绑定到用户控件视图中的相应依赖项属性模型,(3)您从主视图模型访问绑定属性。
-
学习 MVVM。请仔细阅读this。您不会“访问” WPF 中的 UI 来检索/设置数据,仅仅是因为 UI is not Data
标签: c# wpf xaml user-controls