简体   繁体   中英

MVVM WPF DataBinding troubleshooting

In following the MVVM architecture for WPF, learning WPF DataBindings. I have a single instance of an object instantiated at runtime with the XAML code <p:MemoryPersistentStorageBridge x:Key="persistentMemoryBridge" /> within Window Resources. I am trying to obtain data from the object instance, and plop it into a TextBox as an example, but I am not getting any text in that text box.

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>

CodeBehind:

public class MemoryPersistentStorageBridge {

    public MemoryPersistentStorageBridge() {

    }

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

}

You are trying to bind to a method. You need to bind to a property. Or else use an ObjectDataProvider .

So you could do this:

public class MemoryPersistentStorageBridge {

     public MemoryPersistentStorageBridge() {

    }

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

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

}

or even:

public class MemoryPersistentStorageBridge {

     public MemoryPersistentStorageBridge() {

    }

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

}

Of course, in either case we are not handling changing the property and notifying the binding of a change.

The other option is to use the ObjectDataProvider to wrap your method. This is illustrated in the link I provided. But would look something like this:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM