[英]WPF Get Selected Row on Datagrid From Template
App.xaml中
<Application.Resources>
<Style x:Key="datagridRowStyle" TargetType="{x:Type DataGridRow}">
<Setter Property="Height" Value="100"/>
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="{x:Type DataGridRow}">
<Border BorderBrush="Black" BorderThickness="1" MouseDown="row_MouseDown" Background="White">
</Border>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
</Application.Resources>
App.xaml.cs
public partial class App : Application
{
private void row_MouseDown(object sender, System.Windows.Input.MouseButtonEventArgs e)
{
/* I WANT TO KNOW WHICH ROW ON THE DATAGRID I CLICKED */
Navegacao.Switch(new service(/* SO I CAN USE IT HERE */));
}
}
index.xaml
<Border BorderBrush="Black" BorderThickness="1">
<DataGrid Name="datagrid1" Margin="50,50,50,50" ItemsSource="{Binding Path=MyDataBinding}" RowStyle="{StaticResource datagridRowStyle}" HeadersVisibility="None" VerticalScrollBarVisibility="Auto" CanUserAddRows="False"/>
</Border>
index.xaml.cs
public partial class index : Page
{
public index()
{
InitializeComponent();
BindGrid();
}
private void BindGrid()
{
DataSet bind = database.BindGrid("SELECT * FROM (projecto.encomenda INNER JOIN projecto.encom_contem ON id_enc = encom_id) INNER JOIN (SELECT codigo, tipo, descricao FROM Projecto.Produto INNER JOIN Projecto.Servico ON codigo = produto_codigo) AS T1 ON produto_codigo = codigo WHERE estado <> 'Pronto'");
datagrid1.DataContext = bind;
}
}
如您所見,我創建了一個模板,該模板包含數據網格上每一行的邊框。 問題是,我怎么知道我單擊了數據網格的哪一行。 有沒有辦法知道我單擊的是第一個邊框還是第二個邊框?
DataGridRow
將是發件人的可視父級,該發件人將是Border
。 您可以使用VisualTreeHelper
獲得它。
private void row_MouseDown(object sender, MouseButtonEventArgs e)
{
DataGridRow row = (DataGridRow)System.Windows.Media.VisualTreeHelper
.GetParent((Border)sender);
}
附帶說明一下,您可以使用此幫助器方法遞歸地移動到父視覺樹。 如果對鼠標按下的行索引感興趣,也可以很容易地計算出來。
private void row_MouseDown(object sender, MouseButtonEventArgs e)
{
DataGridRow row = FindParent<DataGridRow>((Border)sender);
DataGrid dataGrid = FindParent<DataGrid>(row);
int rowIndex = dataGrid.ItemContainerGenerator.IndexFromContainer(row);
}
private T FindParent<T>(DependencyObject child) where T : DependencyObject
{
var parent = System.Windows.Media.VisualTreeHelper.GetParent(child);
if (parent is T || parent == null)
return parent as T;
else
return FindParent<T>(parent);
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.