我想将SecondViewModel SecondProperty 的值传递给ViewModel myProperty ,并在 TextBlock 上显示该值。 我希望在SecondViewModel中完成编码。 希望一切都清楚。
感谢Advance的帮助。
查看:
EMPLOYEE_ID HOURS_ABSENT DATE 3DAYS 5DAYS
x1 7.500000 2017-01-16 00:00:00.000 0 0
x1 7.500000 2017-01-30 00:00:00.000 0 1
x1 7.500000 2017-01-31 00:00:00.000 0 0
x1 7.500000 2017-02-01 00:00:00.000 0 0
x1 7.500000 2017-02-02 00:00:00.000 0 0
x1 7.500000 2017-02-03 00:00:00.000 0 0
x1 7.500000 2017-02-06 00:00:00.000 0 0
x1 7.500000 2017-02-07 00:00:00.000 0 0
x1 7.500000 2017-05-22 00:00:00.000 0 0
X2 7.500000 2016-11-29 00:00:00.000 1 0
X2 7.500000 2016-11-30 00:00:00.000 0 0
X2 7.500000 2016-12-01 00:00:00.000 0 0
ViewModel:
<TextBlock Text="{Binding Path=myProperty}"/>
SecondViewModel:
private int _myProperty;
public int myProperty
{
get { return _myProperty; }
set { _myProperty = value; OnPropertyChanged("myProperty"); }
}
答案 0 :(得分:1)
根据您的评论,假设ViewModel
拥有SecondViewModel
个项目的集合,则需要为PropertyChangedEvent
的每个实例设置SecondViewModel
来触发{{1} }刷新。例如...
ViewModel.myProperty
顺便说一句,您永远不要使用“魔术字符串”调用public class ViewModel
{
private List<SecondViewModel> _secondViewModels = new List<SecondViewModel>();
public IEnumerable<SecondViewModel> SecondViewModels => _secondViewModels;
public int myProperty => _secondViewModels.Sum(vm => vm.SecondProperty);
public void AddSecondViewModel(SecondViewModel vm)
{
_secondViewModels.Add(vm);
vm.PropertyChanged += (s, e) => OnPropertyChanged(nameof(myProperty));
OnPropertyChanged(nameof(myProperty));
}
}
-改为使用OnPropertyChanged()
。
答案 1 :(得分:-1)
如果需要,您应该创建一个VM数据源以在第一个VM中创建一个依赖项。
public class YourViewModelDataSource
{
private ViewModel viewModel;
private SecondViewModel secondViewModel;
public YourViewModelDataSource(ViewModel viewModel, SecondViewModel secondViewModel)
{
this.viewModel = viewModel;
this.secondViewModel = secondViewModel;
}
public void CreateDataSource()
{
this.secondViewModel.PropertyChanged += this.OnSecondViewModelPropertyChanged;
}
private void OnSecondViewModelPropertyChanged(object sender, PropertyChangedEventArgs e)
{
switch (e.PropertyName)
{
//As pointed in comments, you need to have the second property in your first ViewModel then do this.
case "SecondProperty":
this.viewModel.myProperty = this.secondViewModel.SecondProperty;
break;
}
}
}
在创建VM时,请使用此类创建依赖关系。每当SecondViewModel
SecondProperty更改时,ViewModel
myProperty将被引发。我希望一切都清楚了,让我知道您是否还需要其他东西