gpt4 book ai didi

c# - 在 GridView 中引用单元格中的文本框

转载 作者:行者123 更新时间:2023-11-30 18:45:33 26 4
gpt4 key购买 nike

所以我制作了一个 ListView,在其 View 属性中包含 GridView:

<ListView Grid.Row="1" Name="TicketListView" Margin="20,5,20,5">
<ListView.View>
<GridView>
<GridViewColumn Header="Owned" DisplayMemberBinding="{Binding Owned}"/>
<GridViewColumn Header="Name" DisplayMemberBinding="{Binding Name}"/>
<GridViewColumn Header="Price" DisplayMemberBinding="{Binding Price, ConverterCulture='en-US', StringFormat={}{0:C2}}"/>
<GridViewColumn Header="Amount">
<GridViewColumn.CellTemplate>
<DataTemplate>
<TextBox MinWidth="20" TextAlignment="Center" Margin="5" Text="{Binding Bought, Mode=TwoWay, UpdateSourceTrigger=LostFocus}" />
</DataTemplate>
</GridViewColumn.CellTemplate>
</GridViewColumn>
</GridView>
</ListView.View>
...
</ListView>

在此 ListView 中选择项目时,我想专注于特定的 TextBox,因此您不必单击 TextBox 进行编写,而是可以单击项目(行)并开始更改其值。 (希望你明白 ;( )

这是可能的还是我应该用另一种方式来做这个列表?

最佳答案

您可以处理 ListViewItemPreviewMouseLeftButtonDown 事件,并使用 VisualTreeHelper 获取对 TextBox 的引用类:

<ListView Grid.Row="1" Name="TicketListView">
<ListView.ItemContainerStyle>
<Style TargetType="ListBoxItem">
<EventSetter Event="PreviewMouseLeftButtonDown" Handler="TicketListView_PreviewMouseLeftButtonDown" />
</Style>
</ListView.ItemContainerStyle>
<ListView.View>
<GridView>
<GridViewColumn Header="Owned" DisplayMemberBinding="{Binding Owned}"/>
<GridViewColumn Header="Name" DisplayMemberBinding="{Binding Name}"/>
<GridViewColumn Header="Price" DisplayMemberBinding="{Binding Price, ConverterCulture='en-US', StringFormat={}{0:C2}}"/>
<GridViewColumn Header="Amount">
<GridViewColumn.CellTemplate>
<DataTemplate>
<TextBox MinWidth="20" TextAlignment="Center" Margin="5" Text="{Binding Bought, Mode=TwoWay, UpdateSourceTrigger=LostFocus}" />
</DataTemplate>
</GridViewColumn.CellTemplate>
</GridViewColumn>
</GridView>
</ListView.View>
</ListView>

private void TicketListView_PreviewMouseLeftButtonDown(object sender, MouseButtonEventArgs e)
{
ListViewItem lvi = sender as ListViewItem;
TextBox textBox = GetChildOfType<TextBox>(lvi);
if (textBox != null)
{
textBox.Dispatcher.BeginInvoke(new Action(() =>
{
bool b = textBox.Focus();
Keyboard.Focus(textBox);
}));
}
}

private static T GetChildOfType<T>(DependencyObject depObj) where T : DependencyObject
{
if (depObj == null)
return null;

for (int i = 0; i < VisualTreeHelper.GetChildrenCount(depObj); i++)
{
var child = VisualTreeHelper.GetChild(depObj, i);
var result = (child as T) ?? GetChildOfType<T>(child);
if (result != null) return result;
}
return null;
}

关于c# - 在 GridView 中引用单元格中的文本框,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43675001/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com