2016-01-05 68 views
3

我不知道這裏發生了什麼。當我直接綁定到TextBox的值可以編輯,但我想綁定在ContentControlWPF ContentControl DataTemplate沒有更新值

爲什麼ContentControl不更新ViewModel?

<Window x:Class="WTFWPF.MainWindow" 
     xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" 
     xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" 
     xmlns:d="http://schemas.microsoft.com/expression/blend/2008" 
     xmlns:local="clr-namespace:WTFWPF" 
     xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" 
     xmlns:sys="clr-namespace:System;assembly=mscorlib" 
     Title="MainWindow" 
     Width="525" 
     Height="350" 
     DataContext="{DynamicResource ViewModel}" 
     mc:Ignorable="d"> 
    <Window.Resources> 
     <local:MainViewModel x:Key="ViewModel" /> 
     <DataTemplate DataType="{x:Type sys:Int32}"> 
      <TextBox Text="{Binding Path=., UpdateSourceTrigger=PropertyChanged}" /> 
     </DataTemplate> 
    </Window.Resources> 
    <StackPanel> 
     <TextBlock Margin="5" Text="{Binding Number}" /> 
     <TextBox Margin="5" Text="{Binding Number, UpdateSourceTrigger=PropertyChanged}" /> 
     <ContentControl Margin="5" Content="{Binding Number}" /> 
    </StackPanel> 
</Window> 

回答

-1

使它工作的另一種方法是更改​​模板中的綁定:

<TextBox Text="{Binding Path=DataContext.Number,  
       RelativeSource={RelativeSource AncestorType=ContentControl}, UpdateSourceTrigger=PropertyChanged}" /> 

不幸的是我無法解釋爲什麼您的版本不起作用。

+0

不,不起作用。 –

+0

@CameronMacFarland,更新了答案 – ixSci

0

這似乎工作正常,不知道爲什麼你的版本不工作。

<Window.Resources> 
    <wpfApplication1:MainViewModel x:Key="ViewModel" /> 
     <DataTemplate x:Key="NumberTemplate"> 
      <TextBox Text="{Binding Path=Number, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}" /> 
     </DataTemplate> 
</Window.Resources> 
<StackPanel> 
    <TextBlock Margin="5" Text="{Binding Number}" /> 
    <TextBox Margin="5" Text="{Binding Number, UpdateSourceTrigger=PropertyChanged}" /> 
    <ContentControl Margin="5" 
        Content="{Binding}" 
        ContentTemplate="{StaticResource NumberTemplate}" /> 
</StackPanel>