如果我在数据模板中使用
在代码后台文件MainPage.xaml.cs中定义了一个简单的模型:
{x:Bind {RelativeSource Self}}
,则编译时会出现以下错误:
想法是将模板化的对象传递给类似命令参数的属性。这里是一个示例MainPage.xaml:对象引用未设置为对象的实例。
<Page
x:Class="XBindTest5.MainPage"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="using:XBindTest5"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
mc:Ignorable="d">
<Page.Resources>
<ResourceDictionary>
<local:OpenItemCommand x:Key="OpenCommand"/>
</ResourceDictionary>
</Page.Resources>
<StackPanel Background="{ThemeResource ApplicationPageBackgroundThemeBrush}">
<ItemsControl ItemsSource="{x:Bind NewsItems, Mode=OneWay}">
<ItemsControl.ItemTemplate>
<DataTemplate x:DataType="local:NewsItem">
<StackPanel>
<Button Command="{x:Bind {StaticResource OpenCommand}}" CommandParameter="{x:Bind {RelativeSource Self}}">
<TextBlock Text="{x:Bind Title}"/>
</Button>
</StackPanel>
</DataTemplate>
</ItemsControl.ItemTemplate>
</ItemsControl>
</StackPanel>
</Page>
在代码后台文件MainPage.xaml.cs中定义了一个简单的模型:
using System;
using System.Collections.ObjectModel;
using System.Windows.Input;
using Windows.UI.Xaml.Controls;
namespace XBindTest5 {
public class NewsItem {
public string Title { get; set; }
}
/// <summary>
/// command to open the item
/// </summary>
public class OpenItemCommand : ICommand {
public event EventHandler CanExecuteChanged;
public bool CanExecute(object parameter) {
return true;
}
public void Execute(object parameter) {
// ... example ...
}
}
public sealed partial class MainPage : Page {
public ObservableCollection<NewsItem> NewsItems { get; set; }
= new ObservableCollection<NewsItem>(new[] {
new NewsItem() { Title = "Item 1" },
new NewsItem() { Title = "Item 2" } });
public MainPage() {
this.InitializeComponent();
}
}
}
datatemplate
,所以错过了这个答案。 - ventiseis{Binding}
,那应该可以工作。来自x:Bind
的文档: “您不能使用 {x:Bind} 与 DataContext 属性一起使用,该属性的类型为 Object,并且也可能在运行时更改。” ,即不支持任何依赖于运行时类型信息的技术,例如绑定到模板化对象,无法与x:Bind
一起使用。因此,您需要改回使用{Binding}
。 - Peter DunihoCommandParameter={x:Bind}
起到了预期的作用,但我会确保我发布的任何答案都只包含我个人验证过的代码。 - Peter Duniho