MVVM WPF DataBinding故障排除

时间:2013-01-17 19:56:28

标签: c# wpf xaml data-binding

遵循WPF的MVVM架构,学习WPF DataBindings。我在运行时使用窗口资源中的XAML代码<p:MemoryPersistentStorageBridge x:Key="persistentMemoryBridge" />实例化了一个对象实例。我试图从对象实例获取数据,并将其作为一个示例填入TextBox,但我没有在该文本框中获取任何文本。

XAML:

<Window x:Class="UserConsole.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:p="clr-namespace:PollPublicDataStock;assembly=PollPublicDataStock"
        xmlns:local="clr-namespace:UserConsole"
        Title="MainWindow" Height="900" Width="800">

    <Window.Resources>
        <p:MemoryPersistentStorageBridge x:Key="persistentMemoryBridge" />
    </Window.Resources>


    <Grid Name="grid1" >
         <!--  layout defintions  -->
        <TextBox DataContext="{StaticResource persistentMemoryBridge}"   Text="{Binding Path=GetConnectionString}" Margin="0,327,31,491" Foreground="Black" Background="Yellow"/>
    </Grid>
</Window>

代码隐藏:

public class MemoryPersistentStorageBridge {

    public MemoryPersistentStorageBridge() {

    }

   public string GetConnectionString() {
        return "THISTEXTSHOULDAPPEARINTEXTBOXBUTSADLYDOESNOT";
    }

}

1 个答案:

答案 0 :(得分:3)

您正在尝试绑定到某个方法。您需要绑定到属性。或者使用ObjectDataProvider

所以你可以这样做:

public class MemoryPersistentStorageBridge {

     public MemoryPersistentStorageBridge() {

    }

    public string ConnectionString {
        get { return GetConnectionString(); }
    }

   public string GetConnectionString() {
        return "THISTEXTSHOULDAPPEARINTEXTBOXBUTSADLYDOESNOT";
    }

}

甚至:

public class MemoryPersistentStorageBridge {

     public MemoryPersistentStorageBridge() {

    }

    public string ConnectionString {
        get { return "THISTEXTSHOULDAPPEARINTEXTBOXBUTSADLYDOESNOT"; }
    }

}

当然,在任何一种情况下,我们都不会处理更改属性并通知绑定更改。

另一个选项是使用ObjectDataProvider来包装你的方法。这在我提供的链接中说明。但看起来像这样:

<ObjectDataProvider ObjectInstance="{StaticResource persistentMemoryBridge}"
                  MethodName="GetConnectionString" x:Key="connectionString">
</ObjectDataProvider>