我使用Wpf 4.5和Caliburn Micro 2.0.2 .
我想将Textbox绑定到视图模型的属性 . 该属性(称为ResultData)是TextXmlData类中的对象 . 该类是来自xsd的自动生成的类 . 我使用Microsoft Xsd.exe来实现它 .
这是视图模型
public class ShellViewModel : PropertyChangedBase, IHaveDisplayName
{
public string DisplayName { get; set; }
private TestXmlData _resultData;
public TestXmlData ResultData
{
get { return _resultData; }
set
{
_resultData = value;
NotifyOfPropertyChange(() => _resultData);
}
}
public ShellViewModel()
{
DisplayName = "Shell Window";
}
public void CreateObject()
{
String xmlData = "<TestXmlData><Id>88</Id><Name>What a name</Name></TestXmlData>";
if (ResultData == null) { ResultData = new TestXmlData(); }
XmlSerializer oXmlSerializer = new XmlSerializer(ResultData.GetType());
ResultData = (TestXmlData)oXmlSerializer.Deserialize(new StringReader(xmlData));
// at this point the debugger shows that the ResultData is correctly filled,
// the Name is definitely not empty
}
}
这就是观点
<UserControl x:Class="CMWpfXmlSerializer2Ways.Views.ShellView"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
d:DesignHeight="300"
d:DesignWidth="300"
mc:Ignorable="d">
<Grid Width="300" Height="300">
<StackPanel Width="200"
Height="100"
HorizontalAlignment="Center"
VerticalAlignment="Center">
<Button x:Name="CreateObject"
Width="190"
Content="Create Object from XML" />
<TextBox Width="190"
DataContext="{Binding ResultData}"
Text="{Binding Name}" />
</StackPanel>
</Grid>
</UserControl>
并且TextBox显示始终为空!
我也试过Text =“”,但TextBox仍然显示为空 .
任何人都可以帮助并告诉我上面的代码有什么问题?请随时修改代码 . 提前致谢 .
3 回答
ResultData是ViewModel的一个属性 . 因此,您需要将ViewModel设置为更高级别的DataContext,然后您可以将它的属性用作某个较低级别的绑定源 .
为了运行您的示例,我进行了一些更改并运行如下:
///
///
你有使用Caliburn.MIcro启用调试吗?这可以通过BootStrapper完成 . 这将告诉我们您的视图和视图模型是否正确绑定 .
通常放入引导程序的CTOR中LogManager.GetLog = type => new DebugLog(type);
由于您正在为shellview使用UserControl,我希望看到您的BootStrapper .
我怀疑有些事情是不正确的,或者命名空间没有正确设置,这会导致绑定错误 .
在我一遍又一遍地阅读你的评论,提示,建议和我的代码后,我偶然发现了问题的原因 . 这是我自己的错误(是的,我的愚蠢错误)
我在NotifyOfPropertyChange而不是 the property name ResultData 上使用了 the backing field _resultData ! (请在视图模型中查看属性ResultData的setter)
非常感谢大家!