我有一个带有几个子视图模型的主视图模型
对于每个childVM,我在主视图中定义了以下内容:
<Window.Resources>
<vm:MainVM x:Key="MainVM" />
<DataTemplate DataType="{x:Type vm:ChildVM}">
<view:childview />
</DataTemplate>
</Window.Resources>
在儿童视图中,有一个文本框:
<TextBox>
<i:Interaction.Behaviors>
<behavior:AppendTextBehavior AppendTextAction="{Binding AppendTextAction, Mode=OneWayToSource}" />
</i:Interaction.Behaviors>
</TextBox>
行为类:
public class AppendTextBehavior : Behavior<TextBox>
{
public Action<string> AppendTextAction
{
get { return (Action<string>)GetValue(AppendTextActionProperty); }
set { SetValue(AppendTextActionProperty, value); }
}
public static readonly DependencyProperty AppendTextActionProperty =
DependencyProperty.Register("AppendTextAction", typeof(Action<string>), typeof(AppendTextBehavior));
protected override void OnAttached()
{
base.OnAttached();
SetCurrentValue(AppendTextActionProperty, (Action<string>)AssociatedObject.AppendText);
AssociatedObject.TextChanged += AssociatedObject_TextChanged;
}
void AssociatedObject_TextChanged(object sender, EventArgs e)
{
// does something
}
}
主视图
<TabControl
ItemsSource="{Binding Tabs, Mode=OneWay}"
>
<TabControl.ItemTemplate>
<DataTemplate>
<StackPanel Orientation="Horizontal">
</StackPanel>
..
<Button Content="+" Command="{Binding Source={StaticResource MainVM}, Path=AddTabCommand}" />
</DataTemplate>
</TabControl.ItemTemplate>
<TabControl>
Main ViewModel
private ObservableCollection<ChildVM> tabs;
public ObservableCollection<ChildVM> Tabs
{
get
{
return tabs;
}
set
{
tabs = value;
RaisePropertyChanged(() => Tabs);
}
}
void AddTab()
{
ChildVM tab = new ChildVM();
Tabs.Add(tab);
}
public ICommand AddTabCommand { get { return new MvvmFoundation.Wpf.RelayCommand(AddTab); } }
最后,ChildVM有:
private Action<string> appendTextAction;
public Action<string> AppendTextAction
{
get { return appendTextAction; }
set {
appendTextAction = value;
RaisePropertyChanged(() => AppendTextAction);
}
}
现在,AppendTextAction的VM始终为空,因此绑定无效。
但是,如果我尝试在视图中创建这样的childVM:
<UserControl.DataContext>
<vm:ChildVM>
</UserControl.DataContext>
Binding完美无缺!
显然上面的代码是错误的,因为我不需要再次创建子视图模型
如何使AppendTextAction绑定工作?