我需要創建一個簡單的CRUD,並且我想在不同的頁面中重複使用相同的「模板」。創建一個自定義模板作爲ResourceDictionary並從代碼隱藏中訪問它
MyCrud.xaml(模板)
<ResourceDictionary
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">
<!-- disegno la mia crud-->
<DataTemplate x:Key="MyCrud">
<StackPanel>
<StackPanel Orientation="Horizontal" Margin="0,20,0,20">
<TextBlock Text="Code" FontWeight="Bold" Width="150" FontSize="24"/>
<TextBox x:Name="edtCode" InputScope="Number" Width="300" Margin="20,0,20,0" HorizontalAlignment="Left"/>
</StackPanel>
<StackPanel Orientation="Horizontal" Margin="0,20,0,20">
<TextBlock Text="Vin" FontWeight="Bold" Width="150" FontSize="24"/>
<TextBox x:Name="edtVin" Width="300" Margin="20,0,20,0" HorizontalAlignment="Left"/>
</StackPanel>
<StackPanel Orientation="Horizontal" Margin="0,20,0,20">
<TextBlock Text="Url" FontWeight="Bold" Width="150" FontSize="24"/>
<TextBox x:Name="edtUrl" Width="300" Margin="20,0,20,0" HorizontalAlignment="Left"/>
</StackPanel>
</StackPanel>
</DataTemplate>
然後我在App.xaml中註冊它
<Application.Resources>
<ResourceDictionary>
<ResourceDictionary.MergedDictionaries>
<ResourceDictionary Source="View/MyCrud.xaml"/>
</ResourceDictionary.MergedDictionaries>
</ResourceDictionary>
</Application.Resources>
所以現在我希望把它放在一個頁面,在我的SearchPage.xaml中使用它
SearchPage.xaml
<Page ...bla bla bla>
<ContentControl x:Name="MyTemplate" Content="{Binding}" ContentTemplate="{StaticResource MyCrud}" />
</Page>
目前的佈局完美的作品
的問題是:
- 我如何可以訪問
TextBox
?例如,從SearchPage的代碼隱藏名爲edtVin
。 - 爲什麼
TextBox p= GetTemplateChild("edtVin") as TextBox;
總是空? - 我發現這個solution,這是最好的嗎?
謝謝!
'MyTemplate.ContentTemplate'沒有任何方法,比如'FindName'或者Find-something – ArghArgh
你在說'WPF'嗎?對?方法確實存在,你可以看到[這裏](http://msdn.microsoft.com/en-us/library/system.windows.frameworktemplate.findname(v = vs.110).aspx)。在我的最後編譯罰款。 –
我正在嘗試創建一個Windows應用商店應用,之前我選擇了錯誤的標記 – ArghArgh