x:UWP 应用程序中的绑定和嵌套类 [英] x:Bind and nested class in a UWP application
问题描述
我目前正在开发一个 UWP 应用程序,我想使用已编译的绑定系统.
I am currently working on a UWP application and I would like to use the compiled binding system.
我有一个扩展 Windows.UI.Xaml.Controls.Page
的基础,其中包含一个属性 ViewModel
.
I have a base that extends the Windows.UI.Xaml.Controls.Page
that contains a property ViewModel
.
这里是 ViewModel
属性的基类:
Here the base class of the ViewModel
Property :
public class BaseViewModel : INotifyPropertyChanged
{
public event PropertyChangedEventHandler PropertyChanged;
protected void RaiseOnPropertyChanged([CallerMemberName] string propertyName = "")
{
OnPropertyChanged(propertyName);
}
public void OnPropertyChanged(string propertyName)
{
if (PropertyChanged != null)
{
PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
}
}
}
这里是我的基本页面:
public abstract class BasePage : Page
{
public BaseViewModel ViewModel { get; set; }
}
我的应用程序的页面扩展了 BasePage
并包含扩展 BaseViewModel
类的嵌套(内部)类.这是一个示例代码:
The pages of my app extends the BasePage
and contain a nester (inner) class that extends the BaseViewModel
class. Here a sample code :
public sealed partial class MyPage : BasePage
{
public sealed class MyViewModel : BaseViewModel
{
public string Title
{
get
{
return "Test";
}
}
}
public MyPage()
{
InitializeComponent();
ViewModel = MyViewModel();
}
}
现在,我想将 MyViewModel
类的属性 Title
绑定到我的 UI.根据这篇文章和这个,类似的东西应该可以工作:>
Now, I would like to bind the property Title
of the MyViewModel
class to my UI. According to this article and this one, something like that should work :
<TextBlock
Text="{x:Bind ViewModel.(namespace:MyPage+MyViewModel.Title)}"
/>
不幸的是,我无法编译.由于+"字符,我在生成的文件 MyPage.g.cs
上有几个错误.您知道 UWP 应用程序是否支持嵌套(内部)类上的绑定?也许它仅在 WPF 应用程序上受支持?:(
Unfortunately, I cannot compile. I have several errors on the generated file MyPage.g.cs
due to the "+" char. Do you know if the binding on a nested (inner) class is supported in UWP application ? Perhaps it is supported only on WPF app ? :(
感谢您的帮助!
推荐答案
解决方案是使用新属性以避免强制转换和嵌套类访问 XAML 文件.所以解决方案是使用类似的东西:
The solution is to use a new property in order to avoid the cast and the nested class access into the XAML file. So the solution is to use something like :
public sealed partial class MainPage : BasePage
{
public sealed class MyViewModel : BaseViewModel
{
public string Title
{
get
{
return "Test";
}
}
}
public MyViewModel LocalViewModel
{
get
{
return (MyViewModel) ViewModel;
}
}
public MainPage()
{
this.InitializeComponent();
ViewModel = new MyViewModel();
}
}
因此,使用 x:Bind
语法,XAML 看起来像:
So, using the x:Bind
syntax, the XAML looks like :
<TextBlock Text="{x:Bind LocalViewModel.Title}" />
这篇关于x:UWP 应用程序中的绑定和嵌套类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!