Se uso {x:Bind {RelativeSource Self}}
in un modello di dati, ottengo il seguente errore durante la compilazione:Perché non posso usare {x: Bind {RelativeSource Self}} in un modello dati?
riferimento oggetto non impostato a un'istanza di un oggetto.
L'idea è di passare l'oggetto con modello a una proprietà come un parametro di comando. Ecco un esempio 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>
un semplice modello è definito nel file code-behinde 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();
}
}
}
Se ti chiedi perché ho passato 'command' come' StaticRessource': non ho trovato un modo per fare riferimento a _outer_ proprietà nel modello dati tramite 'X: Bind'. L'uso di una risorsa statica non funziona neanche (crea un'altra NullReferenceException). – ventiseis
Scusa, hai ragione. Dai un'occhiata a questo: http://stackoverflow.com/questions/32372073/is-it-possible-to-use-compiled-binding-xbind-with-reletive-source-templated –
Oh, hai ragione. La risposta dice: _RelativeSource (con x: Bind) non è supportato_. Quindi dovrò cambiare il mio modello .. Ho cercato solo "datatemplate" quindi ho perso questa risposta. – ventiseis