【问题标题】:Access to Usercontrols in WPF访问 WPF 中的用户控件
【发布时间】: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


【解决方案1】:

与 Vlad 和 HighCore 的 cmets 一致:您没有从 MainWindow.xaml.cs 设置 TextBlock。您将其绑定到视图模型。绑定看起来像这样:

<TextBlock Text="{Binding StatusText}" />

上面说:将 Text 属性绑定到当前数据上下文中名为“StatusText”的属性。接下来,创建一个视图模型:

public class ViewModel : INotifyPropertyChanged
{
    public string StatusText
    {
        get { return _statusText; }
        set
        {
            _statusText = value;
            RaisePropertyChanged("StatusText");
        }
    }

    // TODO implement INotifyPropertyChanged
} 

最后,将 MainPage 的 DataContext 设置为视图模型。您可以通过多种方式执行此操作,但为了简单起见,我们在构造函数中执行此操作:

public MainWindow()
{
    InitializeComponent();
    DataContext = new ViewModel { StatusText = "hello world" };
}

现在,我们的想法是将与模型相关的逻辑放入ViewModel。因此,您不需要访问 UI 元素,而是更新 UI 元素绑定到的视图模型属性。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-07-21
    • 1970-01-01
    • 2011-03-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多