Binding问题
下面只是描述问题而写的例子,不用探究逻辑关系的合理与否。
- C# code
public class StudentGroup : ViewModelBase { Student _stu; public Student Stu { get { return _stu; } set { _stu = value; base.OnPropertyChanged("Stu"); } } } public class Student : ViewModelBase { int _age; string _name; public int Age { get { return _age; } set { _age = value; base.OnPropertyChanged("Age"); } } public string Name { get { return _name; } set { _name = value; base.OnPropertyChanged("Name"); } } }
XAML:
- XML code
<DataTemplate x:Key="myParamTemplate"> <Border Name="border" BorderBrush="Aqua" BorderThickness="1" Padding="5" Margin="5"> <Grid> <Grid.RowDefinitions> <RowDefinition/> </Grid.RowDefinitions> <Grid.ColumnDefinitions> <ColumnDefinition /> <ColumnDefinition /> <ColumnDefinition /> </Grid.ColumnDefinitions> <TextBlock Grid.Row="0" Grid.Column="0" Text="Param:"/> <TextBox Grid.Row="0" Grid.Column="1" Text="{Binding Path=Age,UpdateSourceTrigger=PropertyChanged}" /> <TextBlock Grid.Row="0" Grid.Column="2" Text="{Binding Path=Name,UpdateSourceTrigger=PropertyChanged}"/> </Grid> </Border> </DataTemplate><ContentControl Content="{Binding Path=Stu,Mode=TwoWay,UpdateSourceTrigger=PropertyChanged}" ContentTemplate="{StaticResource myParamTemplate}" Background="Red"/>
问题:
按照上面的设计,当myParamTemplate指定的TextBox的值发生改变时,Age值发生改变,Age.set访问器被调用。
那么,怎么样在Age.set访问器被调用的时候,即TextBox发生变化时,Stu.set访问器也被调用,即Age的值发生改变时,它的宿主对象Stu也能发生值改变通知呢?
[解决办法]
这不现实,Stu不可能知道自己属于谁,所以没法通知。
这么诡异的需求是谁想的呢?我猜一定不是业务人员想的,多半是开发人员自己杜撰出来的需求。