[英]WPF ListBox DataTemplate Mouse inside
我有一個ListBox控件和一些用於ListBox的DataTemplates:
<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");
}
看來行得通!
您可以使用將控件模板設置為文本塊的按鈕來代替文本塊,如下所示:
<Button MouseLeftButtonDown="Button_MouseLeftButtonDown_1">
<Button.Template>
<ControlTemplate>
<TextBlock Grid.Column="0" Margin="5,0,5,0" Style="{StaticResource MyLineNumberText}" x:Name="txtBoxLineNumbers"/>
</ControlTemplate>
</Button.Template>
</Button>
然后在后面的代碼中,您將需要:
private void Button_MouseLeftButtonDown_1(object sender, MouseButtonEventArgs e)
{
var textblock = (sender as Button).Template.FindName("txtBoxLineNumbers", (sender as FrameworkElement)) as TextBlock;
textblock.Text = "Hello World";
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.