在我的 MainView 中,有一個包含 ContentControl 的 Frame 應該根據 MainViewModel 中設定的 ViewModel 顯示視圖。
但是,我的 MainView 上沒有顯示任何內容。知道為什么嗎?
主視圖
<Grid>
<Frame HorizontalAlignment="Center">
<Frame.Content>
<ContentControl Content="{Binding TestViewContext}">
<ContentControl.Resources>
<DataTemplate DataType="{x:Type local:TestViewModel}">
<local:TestView />
</DataTemplate>
</ContentControl.Resources>
</ContentControl>
</Frame.Content>
</Frame>
</Grid>
主視圖模型
public class MainViewModel : BaseViewModel
{
private TestViewModel _testViewContext;
public TestViewModel TestViewContext
{
get { return _testViewContext; }
set { _testViewContext = value; OnPropertyChanged(nameof(TestViewContext)); }
}
public MainViewModel()
{
TestViewContext = new TestViewModel();
}
}
TestView
只是一個紅色的頁面
測驗視圖模型
public class TestViewModel : ViewModelBase
{}
uj5u.com熱心網友回復:
Frame有點特別。通常,子控制元件繼承DataContext其父控制元件的。但是,對于Frame,子項不會繼承DataContext。其結果是,你ContentControl擁有DataContext的null。
要驗證這一點,請為您ContentControl提供如下名稱:
<ContentControl x:Name="MyContentControl" Content="{Binding TestViewContext}">
然后在您的建構式中MainView,檢查DataContext如下:
public MainView()
{
// Other code
// Set a breakpoint here and view the DataContext
var dataContext = MyContentControl.DataContext;
}
如需進一步閱讀,您可以閱讀以下帖子: page.DataContext 不是從父框架繼承的?
此外,作為旁注,Frame預期用途是將Source屬性設定為外部檔案。您可能已經注意到,為了在 xaml 中設定子內容,您需要指定<Frame.Content>與其他控制元件不同的內容。
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/342847.html
上一篇:如何在C#中進行單元測驗
下一篇:檔案IO解密程序
