0

在遵循 WPF 的 MVVM 架构中,学习 WPF DataBindings。<p:MemoryPersistentStorageBridge x:Key="persistentMemoryBridge" />我有一个在运行时使用Window Resources中的 XAML 代码实例化的对象的单个实例。我试图从对象实例中获取数据,并将其放入 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";
    }

}
4

1 回答 1

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>
于 2013-01-17T19:58:10.780 回答