WPF ContentControl DataTemplate无法更新值

4

我不知道这里发生了什么。当我直接绑定到一个TextBox时,值可以被编辑,但是我想在一个ContentControl中进行绑定。

为什么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>
2个回答

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>

-1

让它工作的另一种方法是更改模板中的绑定:

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

很抱歉我无法解释为什么您的版本不起作用。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接