我试图在标题中描述的ListBox.DataTemplate中获取Label.Content,我的问题是,我尝试过的所有方式都给出了错误,下面是我的代码。
XAML:
<ListBox x:Name="UsersList" Margin="644,50,50,31.999" ItemsSource="{Binding}" Background="White">
<ListBox.ItemTemplate>
<DataTemplate>
<Grid Height="50" Width="654" MouseEnter="SetHashUser">
<Grid.RowDefinitions>
<RowDefinition/>
<RowDefinition/>
<RowDefinition/>
</Grid.RowDefinitions>
<Label x:Name="HashUser" Content="{Binding Path=USER_HASH}" Visibility="Collapsed"/>
<TextBlock x:Uid="RealAcessoUserDisplay" Text="{Binding Path=NOME}" Grid.RowSpan="1" Grid.Row="0" Background="#FFF0F0F0"/>
<TextBlock x:Uid="RealAcessoUserDisplay" Text="{Binding Path=NIVEL_ACESSO}" Grid.RowSpan="1" Grid.Row="1" Background="#FFF0F0F0"/>
<Menu Grid.RowSpan="1" Grid.Row="2">
<MenuItem Header="Ativar"/>
<MenuItem Header="Desativar"/>
<MenuItem Header="Detalhes" Click="ShowUser"/>
<MenuItem Header="Editar"/>
</Menu>
</Grid>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
数据库连接C#
private void Listtks()
{
SqlConnection con = new SqlConnection();
con.ConnectionString = ConfigurationManager.ConnectionStrings["BellaContext"].ConnectionString;
con.Open();
SqlCommand cmd = new SqlCommand();
cmd.CommandText = "SELECT USER_HASH,NOME,NIVEL_ACESSO FROM USUARIOS";
cmd.Connection = con;
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataTable dt = new DataTable();
da.Fill(dt);
UsersList.ItemsSource = dt.DefaultView;
}
我的目标是点击列表中的某个项目,SelectedRow获取User_Hash.Content。
事件:
private void SetHashUser(object sender, MouseEventArgs e)
{
display.Content = UsersList.SelectedItem(HashUser.Content);
}
错误:
Error:
error CS0103: The name "HashUser" does not exist in the current context
error CS1955: The non-callable member "Selector.SelectedItem" can not be used as
a method.
答案 0 :(得分:1)
ListBox SelectedItem不是方法。它是给出列表框的选择项的属性。在这种情况下,选择项将是DataRow,因为您将DataTable绑定到ListBox。
假设USER_HASH为字符串。请尝试以下代码。
private void SetHashUser(object sender, MouseEventArgs e)
{
var dataRow = UsersList.SelectedItem;
display.Content = dataRow.Field<string>("USER_HASH ");
}