我使用Wpf 4.5和Caliburn Micro 2.0.2。Wpf + Caliburn Micro:將文本框綁定到自定義對象
我想將文本框綁定到視圖模型的屬性。該屬性(稱爲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>
和文本框顯示總是空的!
我也嘗試過使用Text =「{Binding ResultData.Name}」,但TextBox仍然顯示爲空。
任何人都可以幫助並告訴我上面的代碼有什麼問題嗎? 請隨時修改代碼。 在此先感謝。
是你的'ResultData'爲空/空嗎? –
TestXmlData中的屬性 – mvermef
@AbinMathew我ViewModel中的ResultData具有正確的內容,所以它不是空的,也不爲空。 – MagB