我无法获取ControlTemplate中定义的绑定以对抗我的模型。Xamarin表单 - 绑定到ControlTemplate
注意在下面的ControlTemplate中,我使用TemplateBinding绑定到名为Count(橄榄色标签)的属性。我正在使用Parent.Count作为prescribed by this article,但是Parent.Count和计数都不起作用。
下页使用的ControlTemplate。只是为了证明我的ViewModel工作,我也有一个灰色的标签绑定到Count属性。
通知所得到的屏幕。灰色标签显示Count属性。 ControlTemplate的橄榄色标签没有显示任何内容。
我怎样才能让在控件模板标签显示来自视图模型Count属性?
视图模型
namespace SimpleApp
{
public class MainViewModel : INotifyPropertyChanged
{
public MainViewModel()
{
_count = 10;
Uptick = new Command(() => { Count++; });
}
private int _count;
public int Count
{
get { return _count; }
set
{
_count = value;
OnPropertyChanged("Count");
}
}
public ICommand Uptick { get; private set; }
public event PropertyChangedEventHandler PropertyChanged;
protected virtual void OnPropertyChanged(string propertyName)
{
if (PropertyChanged != null)
PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
}
}
}
XAML
<?xml version="1.0" encoding="utf-8" ?>
<ContentPage xmlns="http://xamarin.com/schemas/2014/forms"
xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
xmlns:local="clr-namespace:SimpleApp"
x:Class="SimpleApp.MainPage"
ControlTemplate="{StaticResource ParentPage}">
<StackLayout>
<Button Command="{Binding Uptick}" Text="Increment Count" />
<Label Text="{Binding Count}" BackgroundColor="Gray" />
</StackLayout>
</ContentPage>
后面的代码
通知的BindingContext在此处设置为MainViewModel。我需要使用我自己的ViewModel,而不是背后的代码。
namespace SimpleApp
{
public partial class MainPage : ContentPage
{
public MainPage()
{
BindingContext = new MainViewModel();
InitializeComponent();
}
}
}
控件模板
<?xml version="1.0" encoding="utf-8" ?>
<Application xmlns="http://xamarin.com/schemas/2014/forms"
xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
x:Class="SimpleApp.App">
<Application.Resources>
<ResourceDictionary>
<ControlTemplate x:Key="ParentPage">
<StackLayout>
<Label Text="{TemplateBinding Parent.Count}" BackgroundColor="Olive" />
<ContentPresenter />
</StackLayout>
</ControlTemplate>
</ResourceDictionary>
</Application.Resources>
</Application>
它应该是? – Tony
我已经尝试过,但它也不起作用。 –
还检查NuGets包和Xamarin本身的更新吗?我重新安装了我的电脑,现在没有Xamarin在这里。我想在这里测试。 – Tony