2010-11-20 34 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或其他)?