25

की एक DataTemplate भीतर डाटा के लिए बाध्य करने के लिए मैं निम्नलिखित सरल उदाहरण है:कैसे एक ContentControl

<Window x:Class="TemplateBinding.MainWindow" 
      xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" 
      xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" 
      Title="MainWindow" Height="350" Width="525"> 
     <Window.Resources> 
      <ResourceDictionary> 
       <ResourceDictionary.MergedDictionaries> 
        <ResourceDictionary 
          Source="pack://application:,,,/TemplateBinding;component/PersonTemplate.xaml" /> 
       </ResourceDictionary.MergedDictionaries> 
      </ResourceDictionary> 
     </Window.Resources> 
     <Grid> 
      <ContentControl ContentTemplate="{StaticResource PersonTemplate}" /> 
     </Grid> 
    </Window> 

के साथ:

<ResourceDictionary xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" 
         xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"> 

     <DataTemplate x:Key="PersonTemplate"> 
      <Border Width="100" Height="100" Background="RosyBrown"> 
       <TextBlock Text="{Binding Path=FirstName}" VerticalAlignment="Center" TextAlignment="Center"/> 
      </Border> 
     </DataTemplate> 

    </ResourceDictionary> 
एक अलग ResourceDictionary फ़ाइल में मेरी DataTemplate के रूप में

मैंने अपने मेनकंडो के कॉन्स्ट्रूकोर में अपना डेटा कॉन्टेक्स्ट सेट किया है और इसे इस तरह का पहला नाम प्रदर्शित करके सत्यापित किया है: <ContentControl Grid.Row="1" Content="{Binding FirstName}"/>

एक अन्य परिदृश्य में मैं ListBox के साथ डेटा टेम्पलेट का उपयोग करता हूं, मैं अपने डेटा टेम्पलेट में बिल्कुल बाध्यकारी करता हूं और यह बस काम करता है।

मुझे पता है कि डेटा टेम्पलेट बाध्यकारी को छोड़कर काम कर रहा है क्योंकि यह आकार और पृष्ठभूमि रंग को सही ढंग से दिखाता है।

मैं क्या गलत कर रहा हूं? मेरे डेटा टेम्पलेट में बाध्यकारी कैसे दिखना होगा?

उत्तर

54

आप ContentControl

<ContentControl Content="{Binding}" ContentTemplate="{StaticResource PersonTemplate}" /> 

यह की Content -Property बाध्य करने के लिए नियंत्रण की सामग्री के रूप में ContentControl की DataContext सेट हो जाएगा की जरूरत है।

केवल ContentTemplate संपत्ति सेट करना पर्याप्त नहीं है। ContentControl स्पष्ट रूप से सामग्री के रूप में अपने डेटा कॉन्टेक्स्ट का उपयोग नहीं करता है।

+1

क्या आपके पास इस पर दस्तावेज़ों का लिंक है? यह पूरी तरह से मेरी समस्या का समाधान करता है लेकिन अगर कोई अन्य गॉथस है तो उत्सुक हूं। –

संबंधित मुद्दे