【问题标题】:WPF ContentControl DataTemplate not updating valueWPF ContentControl DataTemplate 不更新值
【发布时间】:2016-01-05 06:36:51
【问题描述】:

我不知道这里发生了什么。当我直接绑定到 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>

【问题讨论】:

    标签: wpf data-binding datatemplate


    【解决方案1】:

    这似乎工作正常,但不确定为什么您的版本不起作用。

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

    【讨论】:

      【解决方案2】:

      另一种使其工作的方法是更改​​模板中的绑定:

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

      很遗憾,我无法解释为什么您的版本不起作用。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2021-12-15
        • 2019-04-12
        • 1970-01-01
        • 1970-01-01
        • 2010-12-27
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多