2010-12-18 92 views
0

我已經在我的資源文件中定義的樣式像下面Silverlight的列表框自定義樣式

<Style x:Name="ListBoxStyle" TargetType="ListBox" > 
    <Setter Property="Template"> 
     <Setter.Value> 
      <ControlTemplate TargetType="ListBox">      
       <StackPanel Orientation="Horizontal"> 
        <TextBlock Text="{Binding Name,Mode=TwoWay}" 
           Margin="5" 
           Foreground="Red"> 
        </TextBlock> 
        <TextBlock Text="{Binding Age,Mode=TwoWay}" 
           Margin="5"> 
        </TextBlock> 
       </StackPanel> 
      </ControlTemplate> 
     </Setter.Value> 
    </Setter>  
</Style> 

我很茫然,什麼把這裏的數據模板

<ListBox x:Name="MyList" ItemsSource="{Binding }"> 
    <ListBox.ItemTemplate> 
     <DataTemplate> 
     </DataTemplate> 
    </ListBox.ItemTemplate> 
</ListBox> 

我嘗試使用內

<ContentPresenter Style="{StaticResource ListBoxStyle}"></ContentPresenter> 

甚至

<ContentControl Style="{StaticResource ListBoxStyle}"></ContentControl>` 

,但得到這個錯誤

無法分配財產 'System.Windows.FrameworkElement.Style'。

如果我想提供自定義樣式,請在DataTemplate標記之間插入什麼?

+0

你想完成什麼?您已經爲ListBox定義了一種樣式,並且您正試圖將其應用於ContentPresenter和ContentControl。那是不對的。 – decyclone 2010-12-18 09:10:41

+0

我想在另一個資源文件中定義列表框的樣式,並在我的page.xaml中指定該樣式。什麼是正確的方式? – user20358 2010-12-18 10:13:07

回答

0

嘗試:

<ListBox x:Name="MyList" ItemsSource="{Binding }"> 
    <ListBox.ItemTemplate> 
     <DataTemplate> 
<StackPanel Orientation="Horizontal"> 
        <TextBlock Text="{Binding Name,Mode=TwoWay}" 
           Margin="5" 
           Foreground="Red"> 
        </TextBlock> 
        <TextBlock Text="{Binding Age,Mode=TwoWay}" 
           Margin="5"> 
        </TextBlock> 
       </StackPanel> 
     </DataTemplate> 
    </ListBox.ItemTemplate> 
</ListBox> 

這shpuld解決您的問題。

如果您定義樣式,您可以定義ListBox的外觀(背景,前景...)。 您可以在此處獲得默認樣式:http://msdn.microsoft.com/en-us/library/cc278062(v = vs.95).aspx

ItemTemplate(它是一個DataTemplate)定義,如何列表中單個元素的數據表示看起來像(您使用綁定等等......)。

如果您想爲單個元素(如MouseOver,Focussed)定義樣式,請爲ListBoxItems編寫樣式。您可以通過ItemContainerStyle將其添加到列表框中。

<ListBox ItemContainerStyle="{StaticResource YourResourceKey}"/>