问题描述
我正在编写Xamarin应用程序,发现无法跨越的WPF之间存在差异.
I'm writing Xamarin application and I found difference between WPF which I cannot cross.
我正在使用Xamarin Forms Labs来获得Repeater控件.
I'm using Xamarin Forms Labs to get Repeater control.
我有一个Repeater,它可以重复DataTemplate:
I have a Repeater, which repeats DataTemplate:
<DataTemplate>
<Button Text="{Binding Text}" Command="{Binding CategorySelectedCommand}" />
</DataTemplate>
但是我想将命令执行移到我的userControl绑定上下文中.
But i would like to move command execution to my userControl Binding Context.
通常使用WPF,它看起来像:
Normally with WPF it would look like:
Command={Binding ElementName=myUserControl, Path=DataContext.CategorySelectedCommand}
但是它没有ElementName属性.
But it does not have ElementName property.
我发现我可以像这样设置按钮的BindingContext:
I have found that I could set BindingContext of my button like this:
BindingContext="{x:Reference myUserControl}"
但是我不能将Text属性绑定到按钮的文本上.
But then I cannot bind Text property to my button's text.
我应该怎么做?
推荐答案
您可以使用Source
属性指定将使用的绑定源,而不是当前的BindingContext
.然后,文本可以来自页面的绑定上下文,而命令可以来自其他地方.
You can use the Source
property to specify a source for the binding that will be used instead of the current BindingContext
. Then the text can come from the page's binding context and the command from somewhere else.
Command="{Binding CategorySelectedCommand, Source={x:Static me:SomeStaticClass.YourUserControl}}"
或
Command="{Binding CategorySelectedCommand, Source={DynamicResource yourUserControlKey}}"
或
Command="{Binding CategorySelectedCommand, Source={x:Reference myUserControl}}"
这是一个完整的例子.一个常见的问题是不实现INotifyPropertyChanged
并在对InitializeComponent()
的调用之后将属性设置为.
Here's a complete example. A common problem is to not implement INotifyPropertyChanged
and set the property after the call to InitializeComponent()
.
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" x:Class="test.MyPage" x:Name="ThePage">
<Label Text="{Binding TextProp, Source={x:Reference ThePage}" HorizontalOptions="Center" VerticalOptions="CenterAndExpand" />
</ContentPage>
背后的代码
public partial class MyPage : ContentPage
{
public MyPage ()
{
this.TextProp = "Some Text";
InitializeComponent ();
}
public string TextProp
{
get;
set;
}
}
这篇关于Xamarin表单绑定按钮父BindingContext的命令的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!