2015-11-05 22 views
1

我在TabControl中有一個TextBox。如果我編輯框中的文本,然後切換到另一個選項卡,文本將丟失。如果我改變焦點(通過鍵盤上的TAB鍵),然後切換到另一個選項卡,則新文本將設置在我的viewmodel中。在TabControl中切換Tab時TextBox Binding不起作用

這裏是我的代碼:

<Window x:Class="TabSwitchProblem.MainWindow" 
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" 
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" 
    Title="MainWindow" Height="350" Width="525"> 
<TabControl ItemsSource="{Binding Pages}"> 
    <TabControl.ContentTemplate> 
     <DataTemplate> 
      <TextBox Text="{Binding PageContent}" /> 
     </DataTemplate> 
    </TabControl.ContentTemplate> 
</TabControl> 

public partial class MainWindow : Window 
{ 
    public ObservableCollection<PageViewModel> Pages 
    { 
     get { return (ObservableCollection<PageViewModel>)GetValue(PagesProperty); } 
     set { SetValue(PagesProperty, value); } 
    } 
    public static readonly DependencyProperty PagesProperty = 
     DependencyProperty.Register("Pages", typeof(ObservableCollection<PageViewModel>), typeof(MainWindow), new PropertyMetadata(null)); 

    public MainWindow() 
    { 
     InitializeComponent(); 
     Pages = new ObservableCollection<PageViewModel>(); 
     Pages.Add(new PageViewModel()); 
     Pages.Add(new PageViewModel()); 
     DataContext = this; 
    } 
} 
public class PageViewModel : DependencyObject 
{ 
    public string PageContent 
    { 
     get { return (string)GetValue(PageContentProperty); } 
     set { SetValue(PageContentProperty, value); } 
    } 
    public static readonly DependencyProperty PageContentProperty = 
     DependencyProperty.Register("PageContent", typeof(string), typeof(PageViewModel), new PropertyMetadata(null)); 
} 

我怎麼能相信,以獲取文本在我的視圖模型更新?

+0

捕捉已更改的選項卡索引並通知您的模型屬性? – grmbl

+0

我知道,如何捕捉SelectionChanged事件。但是,通知我的模型意味着什麼?我怎樣才能獲得TextBox中的值並將其設置在我的模型中? – MTR

回答

0

您可能需要將UpdateSourceTrigger=LostFocus添加到<TextBox Text="{Binding PageContent}" />行。

代碼應該是這樣的

<TextBox Text="{Binding PageContent, UpdateSourceTrigger=LostFocus}" /> 

這應該工作。

+0

不,它沒有幫助。 – MTR

+0

哎呀對不起,它應該是PropertyChanged不LostFocus。我從我所做的事情複製了代碼。 – AndrewJE

1

如果您希望綁定在每次更改值時更新目標,您應該將UpdateSourceTrigger設置爲PropertyChangedTextBox的默認UpdateSourceTriggerText屬性爲LostFocus,它僅在焦點丟失後才更新目標。

<TextBox Text="{Binding PageContent, UpdateSourceTrigger=PropertyChanged}" /> 
+0

這工作。但它具有觸發每個關鍵擊球的副作用。 – MTR

+0

這是'PropertyChanged'的預期行爲,不是副作用。 –

+0

我明白這一點,但我正在尋找一種方式來更新我的財產,當用戶點擊另一個選項卡。我不想每次擊鍵都更新。所以對於我的問題,這是一個副作用的解決方法。但在這種特殊情況下,這是我能接受的副作用。 – MTR