[英]MVVM WPF DataBinding troubleshooting
In following the MVVM architecture for WPF, learning WPF DataBindings. 在遵循WPF的MVVM体系结构之后,学习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. 我在Windows资源中使用XAML代码
<p:MemoryPersistentStorageBridge x:Key="persistentMemoryBridge" />
在运行时实例化了一个对象的实例。 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. 我试图从对象实例中获取数据,并将其放入一个TextBox中作为示例,但在该文本框中没有任何文本。
XAML: 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 .
否则使用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. 另一个选择是使用ObjectDataProvider包装您的方法。 This is illustrated in the link I provided.
我提供的链接对此进行了说明。 But would look something like this:
但是看起来像这样:
<ObjectDataProvider ObjectInstance="{StaticResource persistentMemoryBridge}"
MethodName="GetConnectionString" x:Key="connectionString">
</ObjectDataProvider>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.