This blog was last modified 311 days before.
When using x:Bind
or Binding
in XAML, sometimes, IDE will give warning saying that: Could not resolve binding ...
. This is because the ViewModel binding is completed like below:
// code-behind file
public sealed partial class AcrylicInfo : UserControl
{
public AcrylicInfo()
{
this.InitializeComponent();
// Binding to ViewModel
this.DataContext = new AcrylicInfoViewModel();
}
}
However compiler can't make sure in compile time that what's the type of DataContext
. So we need to make IDE know this info, we should promise to IDE that we will use some class as the ViewModel of this XAML.
For now I only know one method to do this:
Dynamic Cast DataContext In Code Behind File
// code-behind file
public sealed partial class AcrylicInfo : UserControl
{
public AcrylicInfo()
{
this.InitializeComponent();
// Binding to ViewModel
this.DataContext = new AcrylicInfoViewModel();
}
// Here, we dynamically cast DataContext to the ViewModel type.
public AcrylicInfoViewModel ViewModel => (AcrylicInfoViewModel)DataContext;
}
Then we could use this in XAML like below:
<TextBlock Text="{x:Bind ViewModel:InfoText, Mode=OneWay}">
This method is discovered Win Microsoft Community Toolkit MVVM Project.
No comment