2014-08-27 31 views
0

我想問有人爲解決我的問題與動態重寫的DataTemplate的WPF重寫靜態的DataTemplate動態版本

我有準備的DataTemplate

<Window.Resources> 
    <DataTemplate x:Key="pictureTemplate"> 
     <DataTemplate.Resources> 
      <Style TargetType="Image">     
       <Setter Property="Width" Value="180" />       
       <Setter Property="Height" Value="120" /> 
       <Setter Property="Margin" Value="10" /> 
      </Style> 
     </DataTemplate.Resources>   
     <Image Source="{Binding Path=Location}" />    
    </DataTemplate> 
</Window.Resources> 

,然後我有itemcotrol有:

<ItemsControl Name="itemscontrol2" Visibility="Hidden" 
    ItemsSource="{Binding Path=PicturesRight}" ItemTemplate="{StaticResource pictureTemplate}" ItemsPanel="{StaticResource panelTemplate2}" local:DragDropHelper.IsDragSource="true" /> 

一切工作正常。但我想將此代碼重寫爲動態版本,因爲我需要更改屬性WidthHeight的值。

我已經準備本節OD代碼:

DataTemplate dt = new DataTemplate(typeof(ItemsControl)); 
var style = new Style(typeof(Image)); 
var setter = new Setter() 
{ 
    Property = Control.WidthProperty, 
    Value = 200.0 
}; 

style.Setters.Add(setter); 

var setter1 = new Setter() 
{ 
    Property = Control.HeightProperty, 
    Value = 150.0 
}; 

style.Setters.Add(setter1); 

dt.Resources.Add(typeof(Image), style); 
itemscontrol2.ItemTemplate = dt; 

但這個代碼不工作。我不知道問題是什麼,但我已經嘗試了一切可能。 任何人都可以幫助我解決這個問題嗎? 謝謝。

+0

爲什麼不選擇綁定動態屬性。在後面的代碼中編寫模板可能需要使用工廠類。 – pushpraj 2014-08-27 13:59:03

回答

0

而是在代碼編寫的DataTemplate的做它在資源部分如下

<Window.Resources> 
    <DataTemplate x:Key="Temp1"> 
     <TextBlock Text="1"/> 
    </DataTemplate> 
    <DataTemplate x:Key="Temp2"> 
     <TextBlock Text="2"/> 
    </DataTemplate> 
</Window.Resources> 

<ItemsControl Name="itemscontrol2" ItemTemplate="{StaticResource Temp1}" Foreground="White" ItemsSource="{Binding Lista}"/> 

改變在C#

itemscontrol2.ItemTemplate = (DataTemplate)Resources["Temp2"]; 

你爲什麼不使用這樣的事情來調整動態

<Grid Background="CadetBlue"> 
    <Grid.RowDefinitions> 
     <RowDefinition Height="*"/> 
     <RowDefinition Height="0.1*"/> 
    </Grid.RowDefinitions> 
    <ItemsControl Name="control" ItemsSource="{Binding Lista}"> 
     <ItemsControl.ItemTemplate> 
      <DataTemplate> 
       <Image Source="2.jpg"/> 
      </DataTemplate> 
     </ItemsControl.ItemTemplate> 
    </ItemsControl> 
    <Button Content="Change" Grid.Row="1" HorizontalAlignment="Center" VerticalAlignment="Center" Click="Button_Click"/> 
</Grid> 
+0

是的,它是可能的。但我需要動態更改(基於窗口大小)圖像的寬度和高度。我不明白你的例子是否可能改變這個屬性。 – user3120717 2014-08-27 19:36:20

+0

您可以使您的DataTemplate依賴於widt/height。準確解釋你的意思。 – Maximus 2014-08-27 20:00:41

+0

我是WPF中的新成員,我需要改變itemcontrol裏面的圖像大小,以實現wpf窗口的大小。我認爲只是按照上面所述創建新的數據模板,但是這段代碼不起作用,我不明白你的例子:-) – user3120717 2014-08-27 20:22:49