![](/img/trans.png)
[英]How do I add controls to my UserControl when I edit its Collection of controls?
[英]How do I change a controls background on my UserControl when the item is selected
所以我有這個 ListView,它有我的 UserContol 的 DataTemplate 因為我想為我的 ListView 定制設計,它看起來像這樣
<ListView x:Name="LeftMenuListView"
ItemsSource="{Binding MenuItems}"
SelectedItem="{Binding SelectedMenuItem}"
BorderThickness="0"
Width="255">
<ListView.ItemTemplate>
<DataTemplate>
<StackPanel Orientation="Horizontal">
<local:MenuItemControl/>
</StackPanel>
</DataTemplate>
</ListView.ItemTemplate>
</ListView>
Super simple, now when an Item is selected the entire thing changes color which I want it looks great imo
<Style TargetType="ListViewItem">
<Setter Property="FocusVisualStyle" Value="{x:Null}" />
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="ListBoxItem">
<Border
Name="Border"
BorderThickness="0">
<ContentPresenter />
</Border>
<ControlTemplate.Triggers>
<Trigger Property="IsSelected" Value="true">
<Setter TargetName="Border" Property="Background"
Value="#444444"/>
</Trigger>
</ControlTemplate.Triggers>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
但是我的用戶控件中有一個 10 像素寬的邊框,名稱為 SmallBorder。 我想在選擇項目時將其顏色更改為綠色,但我不知道如何訪問該屬性
我的用戶控件
<Grid Background="Transparent">
<TextBlock Text="{Binding Name}"
VerticalAlignment="Center"
Margin="20,0,0,0"
Foreground="#9e9e9e"
FontFamily="Tahoma"/>
<Border Width="10"
HorizontalAlignment="Left"
x:Name="SmallBorder"/>
</Grid>
那么如何在選擇項目時更改SmallBorder
的顏色,然后在未選擇項目時變為透明?
作為用戶控件的 DataContext 的 ViewModel 應該公開一個類似 IsSelected 的屬性,然后您可以添加一個帶有 DataTrigger 的樣式,該樣式對該屬性的更改做出反應。
編輯:
為邊框本身聲明一種樣式,並將其作為靜態資源訪問:它可以放置在 ResourceDictionary 中,在 YourUserControl.Resources 中或與 Border 控件聲明內聯:
<Style TargetType={x:Type Border} x:Key=SelectedBorderStyle>
<Style.Triggers>
<DataTrigger Binding="{Binding IsSelected}" Value="True">
<Setter Property="BorderBrush" Value="Green" />
</DataTrigger>
</Style.Triggers>
</Style>
然后你的 UserControl 將是:
<Grid Background="Transparent">
<TextBlock Text="{Binding Name}"
VerticalAlignment="Center"
Margin="20,0,0,0"
Foreground="#9e9e9e"
FontFamily="Tahoma"/>
<Border Width="10"
Style={StaticResource SelectedBorderStyle}
HorizontalAlignment="Left"/>
</Grid>
請注意,現在您不需要為 Border 設置名稱。
一個Border
是不可見的,除非有東西在里面,但你可以更換Border
與Grid
並使用Style
與DataTrigger
結合到IsSelected
屬性:
<Grid Background="Transparent">
<TextBlock Text="{Binding Name}"
VerticalAlignment="Center"
Margin="20,0,0,0"
Foreground="#9e9e9e"
FontFamily="Tahoma"/>
<Grid Width="10"
HorizontalAlignment="Left"
x:Name="SmallBorder">
<Grid.Style>
<Style TargetType="Grid">
<Style.Triggers>
<DataTrigger Binding="{Binding IsSelected, RelativeSource={RelativeSource AncestorType=ListViewItem}}" Value="True">
<Setter Property="Background" Value="Red" />
</DataTrigger>
</Style.Triggers>
</Style>
</Grid.Style>
</Grid>
</Grid>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.