[英]How to use property in WPF XAML from codebehind
I just want to get my variable from the xaml.cs to use it into my xaml: Here my xaml.cs: 我只想从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();
}
}
}
And here my xaml: 这是我的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>
So, I want to get my "nowStr" to display it in my MainWindow, but I don't really understand how it works, here I am using the binding but nothing happen, I used the local: and still nothing. 因此,我想让我的“ nowStr”在我的MainWindow中显示它,但是我不太了解它是如何工作的,在这里我使用绑定,但是什么也没有发生,我在使用local:仍然没有。 I am a little confused because I search answers in stack but I tryed the responses and nothing worked.
我有些困惑,因为我在堆栈中搜索答案,但是尝试了响应,但没有任何效果。 If you can explain me how I can get my nowStr to my xaml it will be graceful.
如果您能向我解释如何将nowStr转换为我的xaml,那将是很优雅的。
In the constructor of you .cs file add DataContext = this;
在您的.cs文件的构造函数中,添加
DataContext = this;
Now in your TextBlock use Text="{Binding NowStr}"
现在在您的TextBlock中使用
Text="{Binding NowStr}"
And implement INotifyPropertyChanged
on your MainWindow
class and in the setter of your property cal notify 并在
MainWindow
类和属性setter中实现INotifyPropertyChanged
And why are you creating static properties? 以及为什么要创建静态属性?
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.