If I use {x:Bind {RelativeSource Self}}
in a data template, I get the following error while compiling:
Object reference not set to an instance of an object.
The idea is to pass the templated object to a property like a command parameter. Here is an example 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>
A simple model is defined in the code-behinde file 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();
}
}
}
command
asStaticRessource
: I didn't find a way to reference outer properties in the data template viaX:Bind
.Using a static ressource doesn't work either (creates another NullReferenceException). – Tineiddatatemplate
so I missed this answer. – Tineid{Binding}
, that should work. From the docs forx:Bind
: "you cannot use {x:Bind} with the DataContext property, which is of type Object, and is also subject to change at run time.". I.e. no technique that depends on run-time type information, such as binding to the templated object, is going to work withx:Bind
. You need to fall back on{Binding}
instead. – KerguelenCommandParameter={x:Bind}
works as intended, but I try to make sure any answer I post contains only code I have personally verified. – Kerguelen