[英]How click a TextBlock in DataTemplate?
這是我的XAML代碼:
<ListBox ItemsSource="{Binding}" Name="listBox">
<ListBox.ItemTemplate>
<DataTemplate>
<StackPanel Orientation="Horizontal">
<StackPanel Width="370">
<TextBlock Text="{Binding AuthorName}" x:Name="author" MouseEventLeftDown="click"/>
</StackPanel>
</StackPanel>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
和點擊處理程序
private void click(object sender, RoutedEventArgs e)
{
if(author.Text.Equals("Hi"))
{
// Do Something Special
}
}
錯誤是:
錯誤:名稱“作者”在當前上下文中不存在
但是我不明白是什么原因導致了這個錯誤,或者為什么會發生。
具有Name author
TextBlock在您的單擊處理程序范圍內不存在,因為它位於DataTemplate中 。 發生的事情是, author
TextBlock為您的每個數據項(大概是Author類或Book類)創建了一次,因此您實際上可以有數十個名為author
的控件。
最好將點擊處理程序中的sender
投射到文本框中,然后檢查其text屬性。 像這樣:
private void click(object sender, RoutedEventArgs args)
{
var textBox = sender as TextBox;
if(textBox == null)
return;
if(textBox.Text.Equals("hi"))
{
// Do Something Crazy!
}
}
最好使用專為觸摸設計的UI元素,例如HyperlinkButton或Button。 您可以按照自己喜歡的方式設置樣式(尤其是在使用Expression Blend時),但是最好包含一些有關Touch的視覺反饋。
另外-我不確定您的==
代碼-您是否正在將發件人(UI元素)與某些字符串表達式進行比較?
首先,您的TextBlock是在DataTemplate中定義的; 在您的TextBlock上嘗試使用x:Name
而不是Name
。
其次,單擊TextBlock可能會非常棘手,因為您必須在TextBlock中按一個確切的像素。 為了使單擊TextBlock更加容易,您可能需要在TextBlock
上放置一個Background
,因此單擊它會容易得多。 您甚至可以使背景透明:
Background="Transparent"
使用手勢偵聽器創建事件處理程序,例如“ tap”或“ double”等。
用這個...
private void click(object sender, RoutedEventArgs e)
{
var author = (TextBlock)sender;
if (author.Text.Equals("Hi"))
{
// Do Something Special
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.