अगर मैं एक डेटा टेम्पलेट में {x:Bind {RelativeSource Self}}
उपयोग करते हैं, मैं थोड़ी देर के संकलन निम्न त्रुटि मिलती है:मैं डेटा टेम्पलेट में {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>
एक साधारण मॉडल कोड-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();
}
}
}
यदि आपको आश्चर्य है कि मैंने 'कमांड' को 'स्टेटिक रिसोर्स' के रूप में क्यों पारित किया है: मुझे डेटा एक्स टेम्पलेट में 'एक्स: बाइंड' के माध्यम से _outer_ गुणों का संदर्भ देने का कोई तरीका नहीं मिला। एक स्थिर संसाधन का उपयोग करना या तो काम नहीं करता है (एक और NullReferenceException बनाता है)। – ventiseis
क्षमा करें, आप सही हैं। इसके बजाय इसे देखें: http://stackoverflow.com/questions/32372073/is-it-possible-to-use-compiled-binding-xbind-with-reletive-source-templated –
ओह, आप सही हैं। उत्तर कहता है: _RelativeSource (एक्स: बाइंड के साथ) समर्थित नहीं है _। तो मुझे अपना मॉडल बदलना होगा .. मैंने केवल 'डेटामैप्लेट' के लिए खोज की है इसलिए मुझे यह जवाब याद आया। – ventiseis