MVVM WPF数据绑定故障排除
本文关键字:排除 故障 数据绑定 WPF MVVM | 更新日期: 2023-09-27 17:53:55
在学习WPF的MVVM架构时,学习WPF的数据绑定。我有一个对象的单个实例在运行时实例化的XAML代码<p:MemoryPersistentStorageBridge x:Key="persistentMemoryBridge" />
在窗口资源。我试图从对象实例中获取数据,并将其放入文本框中作为示例,但我没有在该文本框中获得任何文本。
<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";
}
}
您正在尝试绑定到一个方法。你需要绑定到一个属性。或者使用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>