[英]How to get the Text from TextBlock inside a DataTemplate in code-behind
[英]How to access the View inside the DataTemplate from Code behind
我綁定我的視圖模型和使用資源字典的視圖,如下所示
<DataTemplate DataType="{x:Type viewmodels:MyViewModel}">
<Views:MyView />
</DataTemplate>
在MyView中,我的dataGrid x:Name =“ BoxDataGrid”與DataGrid.RowDetailsTemplate具有其他dataGrid x:Name =“ SpoolsDataGrid”
如何使用MyViewModel后面的代碼訪問上面的MyView或DataGrid?
原因是,僅當通過事件“ RowDetailsVisibilityChanged”選擇(單擊)主數據網格行時,我才希望在RowDetailsTemplate中加載和顯示內容。
謝謝。
更正:我不好。 我要訪問MyView而不是MyViewModel
這很容易。 MyView
對象中的DataContext
屬性指向MyViewModel
具體對象。 因此,您可以使用XAML綁定到此視圖模型或在代碼隱藏中訪問,例如
MyViewModel model = (MyViewModel) DataContext;
asktomsk的答案是正確的。 您可以通過DataContext屬性訪問ViewModel。
但是,稍加努力,您幾乎總是可以直接從視圖訪問ViewModel。 MVVM或MVC的全部要點是從View到ViewModel沒有依賴關系。
您應該在WPF for MVVM中研究的內容包括:
您需要了解所有這些內容,才能找到針對MVVM遇到的一些問題的優雅解決方案。
如果您希望我們幫助您弄清楚如何做到這一點,而無需通過數據上下文訪問ViewModel,則需要詳細說明要嘗試獲得的行為。
例如,您可以使用轉換器將某些對象的可見性綁定到ViewModel中的布爾值?
如果您已經了解上述所有內容,我們深表歉意。
剛剛使用MVVM Light Toolkit-EventToCommand解決了此問題。 非常歡迎其他更好的建議。
希望此解決方案對其他人有用。 不需要知道該視圖,在我的datagrid視圖中
<i:Interaction.Triggers>
<i:EventTrigger EventName="RowDetailsVisibilityChanged">
<cmd:EventToCommand Command="{Binding RowDetailsVisibilityChangedCommand}" PassEventArgsToCommand="True" />
</i:EventTrigger>
</i:Interaction.Triggers>
在視圖模型中
public RelayCommand<DataGridRowDetailsEventArgs> RowDetailsVisibilityChangedCommand
{
get;
private set;
}
並在viewmodel構造函數中
RowDetailsVisibilityChangedCommand = new RelayCommand<DataGridRowDetailsEventArgs>(e =>
{
DataGrid SpoolsDataGrid = e.DetailsElement as DataGrid;
DataRowView drv = (DataRowView)e.Row.Item;
serialNo = drv.Row["BOX_SERIAL"].ToString();
SpoolsDataGrid.ItemsSource = as400Service.GetSPOOL_BY_SERIAL_NO(serialNo);
});
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.