2016-01-05 5 views
3

Je n'ai aucune idée de ce qui se passe ici. Lorsque je lie directement à un TextBox la valeur peut être modifiée, mais je veux lier dans un ContentControl.WPF ContentControl DataTemplate ne met pas à jour la valeur

Pourquoi ContentControl ne met-il pas à jour le 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> 

Répondre

-1

Une autre façon de le faire fonctionner est de changer la liaison dans le modèle:

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

Malheureusement je ne peux pas expliquer pourquoi votre version ne fonctionne pas.

+0

Non, cela ne fonctionne pas. –

+0

@CameronMacFarland, a mis à jour la réponse – ixSci

0

Cela semble fonctionner, ne sais pas pourquoi votre version ne fonctionne pas.

<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>