我似乎很难找到我的问题的答案(我读过很多,但没有一个对我有用)。我试图在主窗口的DateTime中显示MainWindow.xaml.cs中存储的一些TextBlock。我正在玩它,所以我设置了一个测试代码:
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}" />
发布于 2017-03-26 17:26:41
有几件事要解决。
第一件事是displayTime不是属性,而是一个字段。添加getter/setter,使其属性可用于绑定。
public DateTime displayTime { get; set; }第二件事是Binding Path=displayTime绑定,期望displayTime是DataContext的一个属性。
尝试将窗口DataContext设置为self:
InitializeComponent();
DataContext = this;或在绑定中使用相对源:
<TextBlock Text="{Binding Path=displayTime,
StringFormat='{}{0:h \: m \: ss\.fff}',
Mode=OneWay,
RelativeSource={RelativeSource AncestorType=Window}}"/>从代码隐藏的角度绑定属性是很好的。在更大的视图中,标记和代码可能变得非常复杂,最好为该视图创建一个单独的视图模型(请参阅有关MVVM的内容)。
https://stackoverflow.com/questions/43031838
复制相似问题