2010-11-20 35 views
3

我有一个TabControl绑定到ICollectionViewObservableCollection<EditorTabViewModel>派生。我认为相当标准的MVVM多文档模式?无论如何,EditorTabViewModel有一个属性Content包含要显示的字符串。我发现,结合工作...绑定不提交?

// Add 2 default tabs for a test, also set their Content property to the respective values ... 
_tabs.Add(new EditorTabViewModel { Content = "Tab 1" }); 
_tabs.Add(new EditorTabViewModel { Content = "Tab 2" }); 

它的值是正确呈现

XAML

<!-- DataTemplate to render EditorTabViewModels --> 
<DataTemplate DataType="{x:Type vm:EditorTabViewModel}"> 
    <me:MarkdownEditor 
     TextContent="{Binding Path=Content.Content, RelativeSource={RelativeSource Mode=TemplatedParent}, Mode=TwoWay}" 
     Options="{Binding Path=Options, RelativeSource={RelativeSource AncestorType={x:Type Window}}}" /> 
</DataTemplate> 

结果

但是,当我改变值,开关选项卡和回报,我得到的字符串在构造函数中重新设置......显示在this video (on screenr)

Visual Studio Solution

+0

Mediafire不允许我下载源代码。据推测,因为来自我所在地区的很多人正在尝试从它下载​​某些内容。 – 2010-11-20 14:48:39

回答

0

将MarkdownEditor.xaml中TextBox“txtEditor”的UpdateSourceTrigger更改为PropertyChanged。 TextBox的默认UpdateSourceTrigger值为LostFocus,并且在更改选项卡时从未引发该事件。这就是为什么它恢复到以前的值

<TextBox Grid.Row="1" x:Name="txtEditor" AcceptsReturn="True" 
     Text="{Binding TextContent, UpdateSourceTrigger=PropertyChanged}" 
     FontFamily="{Binding Path=Options.FontFamily}" 
     FontSize="{Binding Path=Options.FontSize}" 
     FontWeight="{Binding Path=Options.FontWeight}" 
     Background="{Binding Path=Options.Background}" 
     Foreground="{Binding Path=Options.Foreground}" /> 
+0

虽然我不确定,但这种解决方案可能会导致高内存消耗。您将在'txtEditor'中的每个文本更改上分配一个新字符串。对于短文本来说它是实惠的,但不适用于文档编辑器。最好勾选LostFocus事件或其他内容。 – 2010-11-22 12:42:09

+0

@ alpha-mouse由于.NET垃圾收集器的工作原理,创建大量(大量!)小型短暂对象(如字符串)很少成为问题。 – Bevan 2011-01-05 21:36:56

+0

@Bevan:我们在这里谈论文本编辑器。所以这些字符串不会特别地_small_。 – 2011-01-06 10:52:41

0

我会假设MarkdownEditor.TextContent财产并没有告诉任何人它的价值被改变了,所以绑定机制并不会将它写入EditorTabViewModel.Content的新值。如果TextContentMarkdownEditor的依赖项属性,那么是否可以确保它从您用于实际编辑文本的控件接收更改的文本(TextBox或其他)?