[英]How to use property in WPF XAML from codebehind
我只想从xaml.cs中获取变量,以将其用于我的xaml中:这是我的xaml.cs:
using System;
using System.Globalization;
namespace Calendar
{
public partial class MainWindow : Window
{
private static CultureInfo french =
CultureInfo.GetCultureInfo("fr-FR");
private static string nowStr =
DateTime.Now.ToString(French);
public static string NowStr { get => nowStr; set => nowStr = value; }
public static CultureInfo French { get => french; set => french = value; }
public MainWindow()
{
InitializeComponent();
}
}
}
这是我的xaml:
<Window x:Class="Calendar.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:Calendar"
mc:Ignorable="d"
Title="MainWindow" Height="350" Width="525">
<Grid RenderTransformOrigin="0.425,0.522">
<TextBlock Text="{Binding Path=MainWindow.nowStr}"></TextBlock>
</Grid>
</Window>
因此,我想让我的“ nowStr”在我的MainWindow中显示它,但是我不太了解它是如何工作的,在这里我使用绑定,但是什么也没有发生,我在使用local:仍然没有。 我有些困惑,因为我在堆栈中搜索答案,但是尝试了响应,但没有任何效果。 如果您能向我解释如何将nowStr转换为我的xaml,那将是很优雅的。
在您的.cs文件的构造函数中,添加DataContext = this;
现在在您的TextBlock中使用Text="{Binding NowStr}"
并在MainWindow
类和属性setter中实现INotifyPropertyChanged
以及为什么要创建静态属性?
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.