I am a complete newb into XAML. I have previously worked with C#, C++, and ASP.net however if that helps. Here is what I want to do; dynamically display a string variable (lets call it "debt") that is declared in the c# code behind. Is there a simple way to do this using a TextBlock call?
在后面的代码中:
TextBox.Text = debt;
You should use the Binding in WPF, of course you can do it in the code behind but what if your variable debt changed for any reason.
Declare a dependency property like the code below, it'll auto implement the NotifyPropertyChanged wich will update your UI in case your variable value changed at runtime.
public partial class MainWindow : Window
{
public string Debt
{
get { return (string)GetValue(DebtProperty); }
set { SetValue(DebtProperty, value); }
}
public static readonly DependencyProperty DebtProperty =
DependencyProperty.Register("Debt", typeof(string), typeof(MainWindow), new PropertyMetadata(string.Empty));
public MainWindow()
{
InitializeComponent();
this.DataContext = this;
this.Debt = "Test";
}
}
And then in your Xaml just declare your textblock (or textbox if you want to modify the variable debt) and bind its Text property to your variable Debt.
<TextBlock Text="{Binding Path=Debt, UpdateSourceTrigger=PropertyChanged}" />
It seems to be a lot of code for just setting a text property but it's always better to user WPF binding.
Even better you can use MVVM pattern.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.