如何强制从TemplateControl更新数据源

时间:2011-12-23 21:42:51

标签: wpf data-binding controltemplate

我通过解决一个简单的问题而弄清楚了。我有一个填充模板属性的自定义控件。模板是一个带有TextBox的简单Grid。这个文本框与setter和getter绑定到singleton的proprty。如何以编程方式强制TextBox从单例中读取值并将其放回?

<Window x:Class="Spike.Window1"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        Title="Window1" Height="305" Width="521" xmlns:my="clr-namespace:Spike" xmlns:Data="clr-namespace:Spike.Data">
    <Grid>
        <Grid.Resources>
            <ControlTemplate x:Key="editingTemplate">
                <Grid>
                    <TextBox Text="{Binding Source={x:Static Data:MyClass.Instance}, Path=Value2}"/>
                </Grid>
            </ControlTemplate>
        </Grid.Resources>

        <UserControl Template="{StaticResource editingTemplate}" HorizontalAlignment="Left" Margin="58,60,0,0" x:Name="myUserControl1" VerticalAlignment="Top" Height="75" Width="284" />
        <Button Content="Update source" Height="23" HorizontalAlignment="Left" Margin="184,23,0,0" Name="button1" VerticalAlignment="Top" Width="111" Click="button1_UpdateSource" Focusable="False" />
        <Button Content="Update control" Focusable="False" Height="23" HorizontalAlignment="Left" Margin="58,23,0,0" Name="button2" VerticalAlignment="Top" Width="111" Click="button2_UpdateControl" />
    </Grid>
</Window>
namespace Spike.Data
{
    public class MyClass
    {
        private static readonly MyClass MyClassInstance = new MyClass();

        public MyClass()
        {
            Value1 = "value1";
            Value2 = "value2";
        }

        public static MyClass Instance
        {
            get { return MyClassInstance; }
        }

        public string Value1 { get; set; }

        public string Value2 { get; set; }
    }
}

换句话说,应该在 button2_UpdateControl button1_UpdateSource 方法中实施哪些内容?

提前感谢您的任何帮助

1 个答案:

答案 0 :(得分:0)

不应手动重新调用Binding。相反,您应该尝试使当前的绑定机制正常工作。 您的TextBox应该绑定到DependancyProperty,或者TextBox的DataContext应该实现INotifyPropertyChanged。 像这样定义Value2属性:

public static readonly DependencyProperty Value2Property = 
    DependencyProperty.Register("Value2", typeof(string), typeof(MyClass), new PropertyMetadata(string.Empty));

public string Value2
{
    get { return (string)GetValue(Value2Property); }
    set { SetValue(Value2Property, value); }
}

此外,MyClass应该实现UIElement。