Reputation: 4869
Hi i have 2 listviews in a grid. Each listview contains a textbox and both textboxes in both listviews have the same text. When i select part of the text in either textbox, the other textbox will select the same part of the text as well.
can binding between two textbox in 2 different listview be done?
Upvotes: 1
Views: 3150
Reputation: 36310
As AngelWPF writes, the Selection*-properties are not dependency properties so you cannot use databinding on them.
What you can do though, is to add your own subcalss of the TextBox that has dependency properties that replace the original properties. These can be implemented as regular dependency properties using the same names as the original properties, but the definition of them must be public new
to replace the originals.
I will not post an entire code sample here (too much code and I don't have it on this computer), but you can do something like the following:
public class BindableSelectionTextBox : TextBox
{
// Defines the dependency property as normal
public static readonly DependencyProperty SelectedTextProperty =
DependencyProperty.RegisterAttached(SelectedText, typeof(string),
typeof(BindableSelectionTextBox),
new FrameworkPropertyMetadata("", SelectedTextPropertyChanged));
private static void SelectedTextPropertyChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
{
var textBox = (TextBox)d;
textBox.SelectedText = (string)e.NewValue;
}
public new string SelectedText
{
get { return (string)GetValue(SelectedTextProperty); }
set
{
if(value != SelectedText)
{
SetValue(SelectedTextProperty, value);
}
}
}
public BindableSelectionTextBox()
{
SelectionChanged += OnSelectionChanged;
}
private void OnSelectionChanged(object sender, RoutedEventArgs e)
{
SelectedText = base.SelectedText;
}
}
Now, you must repeat this for the SelectionStart
and SelectionLength
properties and you should be done.
Upvotes: 2
Reputation: 19885
Sadly because SelectionText
, SelectionLength
and SelectionStart
are not dependency properties, the two textboxes canot be two way bound on these properties.
You will have to write an attached behavior, attach one textbox to another and handle TextBox.SelectionChangedEvent
for both, and synchronize the other when the event is handled.
Upvotes: 1