如何从列表框内的文本块中检索文本并在文本框中显示文本?
我想做什么
首先,我希望能够从列表框中的文本块中复制文本
然后我想在文本框中显示文本
我尝试使用可视树辅助工具,但显然它找不到'FindName'方法。有没有更好的方法来实现这一目标?
XAML代码
<ListBox Name="ChatDialogBox" Height="550" ItemsSource="{Binding Path=Instance.Messages,Source={StaticResource Binder}}" >
<ListBox.ItemTemplate>
<DataTemplate>
<Grid>
<TextBlock Name="ChatMessage" Text="{Binding Text}" TextWrapping="Wrap" Width="430">
<toolkit:ContextMenuService.ContextMenu>
<toolkit:ContextMenu Name="ContextMenu" >
<toolkit:MenuItem Name="Copy" Header="Copy" Click="Copy_Click" />
</toolkit:ContextMenu>
</toolkit:ContextMenuService.ContextMenu>
</TextBlock>
</Grid>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
代码背后
private void Copy_Click(object sender, RoutedEventArgs e)
{
ContentPresenter myContentPresenter = FindVisualChild<ContentPresenter>(ChatDialogBox);
DataTemplate myDataTemplate = myContentPresenter.ContentTemplate;
TextBlock target = (TextBlock)myDataTemplate.FindName("ChatMessage", myContentPresenter);
}
private childItem FindVisualChild<childItem>(DependencyObject obj) where childItem : DependencyObject
{
for (int i = 0; i < VisualTreeHelper.GetChildrenCount(obj); i++)
{
DependencyObject child = VisualTreeHelper.GetChild(obj, i);
if (child != null && child is childItem)
return (childItem)child;
else
{
childItem childOfChild = FindVisualChild<childItem>(child);
if (childOfChild != null)
return childOfChild;
}
}
return null;
}
Binder Class
public class Binder : INotifyPropertyChanged
{
static Binder instance = null;
static readonly object padlock = new object();
public Binder()
{
Messages = new ObservableCollection<Message>();
}
public static Binder Instance
{
get
{
lock (padlock)
{
if (instance == null)
{
instance = new Binder();
}
return instance;
}
}
}
private ObservableCollection<Message> messages;
public ObservableCollection<Message> Messages
{
get
{
return messages;
}
set
{
if (messages != value)
{
messages = value;
NotifyPropertyChanged("Messages");
}
}
}
public event PropertyChangedEventHandler PropertyChanged;
private void NotifyPropertyChanged(String info)
{
if (PropertyChanged != null)
{
Deployment.Current.Dispatcher.BeginInvoke(() => { PropertyChanged(this, new PropertyChangedEventArgs(info)); });
}
}
}
邮件类
public class Message
{
public string Text { get; set; }
}
答案 0 :(得分:1)
有一种间接但更简单的方法来检索文本块的内容。
在click事件中,您可以使用DataContext
属性
private void Copy_Click(object sender, RoutedEventArgs e)
{
var model = (Message)((FrameworkElement)sender).DataContext;
// Display model.Text in your TextBlock
}
只需将您分配给列表框的ItemsSource的对象类型替换为Message
。