我有一个 ListBox 控件和一些用于 ListBox 的 DataTemplate:
<DataTemplate DataType="{x:Type local:LogEntry}" x:Key="lineNumberTemplate">
<Grid IsSharedSizeScope="True">
<Grid.ColumnDefinitions>
<ColumnDefinition SharedSizeGroup="Index" Width="Auto"/>
<ColumnDefinition/>
</Grid.ColumnDefinitions>
<Grid>
<Rectangle Fill="{Binding Path=LineNumbersBackgroundColor, ElementName=LogViewerProperty}" Opacity="0.4" />
<TextBlock Grid.Column="0" Margin="5,0,5,0" Style="{StaticResource MyLineNumberText}" x:Name="txtBoxLineNumbers" />
</Grid>
<TextBlock Grid.Column="1" Margin="5,0,0,0" Style="{StaticResource MyTextEditor}" />
</Grid>
</DataTemplate>
<ListBox ItemsSource="{Binding}" x:Name="LogViewer" Background="{Binding Path=TextEditorBackgroundColor, ElementName=LogViewerProperty}" Style="{StaticResource MyListBox}" Foreground="{Binding Path=TextEditorForegroundColor, ElementName=LogViewerProperty}" ItemTemplateSelector="{StaticResource templateSelector}" Loaded="LogViewer_Loaded" SelectionMode="Extended" ItemContainerStyle="{StaticResource LeftAligned}" />
当按下鼠标左键并且鼠标在 TextBlock txtBoxLineNumbers 内时,是否可以在运行时更改 ItemContainerStyle?
欢迎所有提示!
更新
好的,我找到了解决方案:
var items = (sender as ListBox).SelectedItems;
foreach (LogEntry item in items)
{
ListBoxItem myListBoxItem = (ListBoxItem) (LogViewer.ItemContainerGenerator.ContainerFromItem (item));
ContentPresenter myContentPresenter = FindVisualChild<ContentPresenter> (myListBoxItem);
DataTemplate myDataTemplate = myContentPresenter.ContentTemplateSelector.SelectTemplate (myListBoxItem, LogViewer);
if (!mouseMove && leftMouseButtonDown)
{
TextBlock target = (TextBlock) myDataTemplate.FindName ("txtBoxLineNumbers", myContentPresenter);
if (target.IsMouseOver && leftMouseButtonDown)
{
System.Windows.Resources.StreamResourceInfo info = Application.GetResourceStream (new Uri ("/LogViewer;component/Template/RightArrow.cur", UriKind.Relative));
Cursor = new Cursor (info.Stream);
fullSelectionBox = true;
LogViewer.ItemContainerStyle = null;
break;
}
LogViewer.ItemContainerStyle = (Style) FindResource ("LeftAligned");
}
它似乎工作!