问题
Let me explain my question by an Image
I have MVVM structure in My project.
I have two textblocks, Textblock 1
and textblock 2
. Now I want textblock2's
Text same as Textblock1's
Text, whenever Textblock1's Text changed.
but I should be able to set Textblock2's
Text different from Textblock1's
.
So I am setting Oneway binding of Textblock1's Text Property.
How Can I get the Text property of Textblock2's
In MVVM. If I create a property for Textblock2's
Text property, I wont be able to bind Textblock1's
text to textblock2
.
Let me know if I want to clear my question further.
Thanks in anticipation.
回答1:
Use two properties in VM, and implement the equal/override logic there. That's exactly the kind of stuff VMs are good in.
VM
Prop1 <-- Binding- TextBlock1
Prop2 <-- Binding- TextBlock2
The Prop1 setter is implemented such that it also updates Prop2 (don't forget INotifyPropertyChanged), if you set Prop2 make it to switch to and keep the different value.
回答2:
Here is the code to go along with flq's answer:
public class MyViewModel : INotifyPropertyChanged
{
public event PropertyChangedEventHandler PropertyChanged;
private string _text1;
private string _text2;
public string Text1
{
get { return _text1; }
set
{
if (_text1 != value)
{
_text1 = value;
RaisePropertyChanged("Text1");
Text2 = _text1;
}
}
}
public string Text2
{
get { return _text2; }
set
{
if (_text2 != value)
{
_text2 = value;
RaisePropertyChanged("Text2");
}
}
}
public MyViewModel()
{
}
private void RaisePropertyChanged(string propertyName)
{
if (PropertyChanged != null)
{
PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
}
}
}
Be sure to change your bindings to two-way.
EDIT:
Here is the XAML:
<TextBox Text="{Binding Text1, UpdateSourceTrigger=PropertyChanged}" />
<TextBox Text="{Binding Text2}" />
Setting UpdateSourceTrigger=PropertyChanged allows the property to be updated as you type, so TextBox2 will update as you type. (FYI - The default bindings for TextBoxes is Two-Way)
来源:https://stackoverflow.com/questions/14766798/how-to-bind-one-texblock-value-to-other-textblock-one-way-and-get-value-in-mvvm