Unable to copy text to clipboard while bound

2019-09-08 16:13发布

问题:

I am having a textblock element in WPF application that is bound to a combobox and I want the textbox text value to be copied to the clipboard when a button is pressed but i am unable to get the text value in the code behind as i am unable to use the textbox name itself to refer to its properties. This is a follow up to my previous question over here Getting XML element from a Combobox item the code is over there so donot want to extend the question these are the simple two lines of code

<TextBox Grid.Column="1" 
    Text="{Binding SelectedItem.Value, ElementName=QueryChooser}" 
    Grid.ColumnSpan="2" Grid.Row="1" Height="200" HorizontalAlignment="Left" 
    Name="textBlock1"  VerticalAlignment="Top" Width="481" />

回答1:

Firstly, I would recommend looking into the MVVM design pattern if you are serious about doing any WPF development. If you are using MVVM, then use an MVVM framework. It will make your life considerably easier.

Secondly, you need some kind of mechanism for invoking verbs on your data context (a view model in MVVM). WPF provides commanding, and MVVM frameworks provide other techniques and variations.

Once you have this mechanism, then you have the query text in your SelectedQuery property, so you can copy SelectedQuery.Value (a string) to the clipboard.



回答2:

write CopyingCellClipboardContent event in your datagridTemplateColumn in xaml. In code behind in this event write this,

if (dataGrid1.CurrentCell != null && dataGrid1.CurrentCell.Column == e.Column) { dataGrid1.SelectionUnit=Microsoft.Windows.Controls.DataGridSelectionUnit.Cell; e.Content = ((System.Data.DataRowView)(dataGrid1.CurrentCell.Item)).Row.ItemArray[4].ToString(); } else e.Content = true;

Thanks..