What is the Different between binding and x:bind in UWP.
I do not know how to choose in my app.
please reply me soon. thanks
What is the Different between binding and x:bind in UWP.
I do not know how to choose in my app.
please reply me soon. thanks
Hello,
Welcome to Microsoft Q&A!
First, the DataContext of x:bind is current page, it will find the property in the current Code-Bebind class. But for Binding, assumes, by default, that you're binding to the DataContext of your markup page, so you need to set DataContext explicitly for Binding.
And the default mode of x:bind is oneTime, it means it will change the value one time. So in general, you need to set the mode as oneWay which is the default mode of Binding. In addition, x:bind generates source code at compile-time, the binding will take effect at runtime, so x:bind is more faster. For more details about their difference, you can refer to this document.
Update:
First, I create a simple ViewModel which contains a Text property.
public class MyViewModel : INotifyPropertyChanged
{
public event PropertyChangedEventHandler PropertyChanged = delegate { };
public string text { get; set; }
public string Text {
get {
return text;
}
set {
text = value;
OnPropertyChanged();
}
}
public MyViewModel() {
this.Text = "first";
}
public void OnPropertyChanged([CallerMemberName] string propertyName = null)
{
// Raise the PropertyChanged event, passing the name of the property whose value has changed.
this.PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
}
}
For x:bind:
We need to set the mode to OneWay and don't need to explicitly specify its context.
.xaml:
< TextBlock Text="{x:Bind VM.Text,Mode=OneWay}">
.cs:
public MainPage()
{
this.InitializeComponent();
VM = new MyViewModel();
}
public MyViewModel VM { get; set; }
For Binding:
We don't need to set the mode to OneWay since its default mode is OneWay and we need to explicitly specify its context.
.xaml:
< TextBlock Text="{Binding VM.Text}">
.cs:
public MainPage()
{
this.InitializeComponent();
VM = new MyViewModel();
this.DataContext = this; // it means current context is this page.
}
public MyViewModel VM { get; set; }
When you want to reassign Text:
private void Button_Click(object sender, RoutedEventArgs e)
{
VM.Text = "Hello";
}
do you mean that you do not need to use datacontext in x:bind? Can you share two examples to explain your comomt? thanks.
8 people are following this question.
How to write and read multiple types of data using Data Writer and Data Reader
Consuming UWP mail api from WPF Desktop Bridge App
Get Network usage information in UWP apps
How to Get/Set Cookies in Windows.Web.Http API
Switch the ListView Datatemplate from one data template to another data template?