最近在做一個課程設計,主要做一個聊天軟件,其中要做一個好友列表,雖然做的不是很精美,但是學習還是有用的。
這個模板主要是實現一個帶有圖標的ListBoxItem的效果
如下圖:
這個ListBoxItem是寫在APP.XML中的以個樣式模板,每次添加的ListBoxItem都會應用到,動態的也會應用這個樣式。模板在msdn裏面有
下面是代碼
<Style TargetType="{x:Type ListBoxItem}">
<Setter Property="SnapsToDevicePixels" Value="true"/>
<Setter Property="OverridesDefaultStyle" Value="true"/>
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="ListBoxItem">
<Border
Name="Border"
Padding="2"
SnapsToDevicePixels="true">
<Grid>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="30"/>
<ColumnDefinition/>
</Grid.ColumnDefinitions>
<Image Width="30" Height="30" Source="Img/header.ico" Grid.Column="0"/>
<ContentPresenter Grid.Column="1" VerticalAlignment="Center" ></ContentPresenter>
</Grid>
</Border>
<ControlTemplate.Triggers>
<Trigger Property="IsSelected" Value="true">
<Setter TargetName="Border" Property="Background"
Value="Blue"/>
</Trigger>
<Trigger Property="IsEnabled" Value="false">
<Setter Property="Foreground"
Value="White"/>
</Trigger>
</ControlTemplate.Triggers>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
引用代碼
<ListBox>
<ListBoxItem>我去你妹的</ListBoxItem>
<ListBoxItem>我去你妹的</ListBoxItem>
<ListBoxItem>我去你妹的</ListBoxItem>
<ListBoxItem>我去你妹的</ListBoxItem>
</ListBox>
希望這段代碼對正在學習WPF的同學有幫助