【问题标题】:Binding property from MainWindow to TextBlock in MainWindow将 MainWindow 中的属性绑定到 MainWindow 中的 TextBlock
【发布时间】:2017-03-26 17:05:23
【问题描述】:

我似乎很难找到我的问题的答案(我已经阅读了很多,但没有一个对我有用)。我正在尝试在位于主窗口的 TextBlock 中显示存储在 MainWindow.xaml.cs 中的一些 DateTime。我正在玩它,所以我设置了一个测试代码:

MainWindow.xaml.cs:

public partial class MainWindow : Window
{
    public DateTime displayTime;

    public MainWindow()
    {
        displayTime = new DateTime(1,1,1,0,1,21,306);
        InitializeComponent();
    }
}

MainWindow.xaml:

<Window x:Class="Project1.MainWindow"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
    xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
    xmlns:local="clr-namespace:Project1"
    mc:Ignorable="d"
    Title="Main Window" MinHeight="450" Height="450" MinWidth="650" Width="650">

<TextBlock Text="{Binding Path=displayTime, StringFormat='{}{0:h \: m \: ss\.fff}', Mode=OneWay}" />

【问题讨论】:

    标签: c# .net wpf xaml data-binding


    【解决方案1】:

    有几件事需要解决。

    第一件事是displayTime不是属性,它是一个字段。添加 getter/setter 使其属性可用于绑定。

    public DateTime displayTime { get; set; }
    

    第二件事是Binding Path=displayTime绑定期望displayTime是DataContext的一个属性。

    尝试将 Window DataContext 设置为 self:

    InitializeComponent();
    DataContext = this;
    

    或在绑定中使用相对源:

    <TextBlock Text="{Binding Path=displayTime, 
                      StringFormat='{}{0:h \: m \: ss\.fff}', 
                      Mode=OneWay, 
                      RelativeSource={RelativeSource AncestorType=Window}}"/>
    

    可以在小视图中从代码隐藏中绑定属性。在较大的视图中,标记和代码会变得相当复杂,建议为该视图创建一个单独的视图模型(阅读有关 MVVM 的信息)。

    【讨论】:

    • @Krepsy3,如果绑定出现问题,请在运行应用程序时检查 Visual Studio 输出窗口。 VS 在运行时报告绑定错误(错误的路径、来源、类型等)
    • @Krepsy3,Visual Studio 输出窗口
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-07-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多