[英]In WPF, can I somehow use TemplateBinding to set the CornerRadius of a templated Button?
[英]WPF TemplateBinding to DataContext of templated parent
我們在四個XAML視圖中有四個相同的帶有網格的彈出窗口。 我想將XAML移至模板,然后通過樣式將其應用於所有這四個控件中的ContentControls。 麻煩在於傳遞網格中項目的來源。 我們可以從四個不同的視圖模型中分別獲得。 在每種情況下都不同,唯一的不同是四種情況。 我可能最終會一致地重命名它們,但是我想這是一個單獨的問題。
顯然我根本不了解TemplateBinding。 如何將模板子級的屬性綁定到要將模板應用到的ContentControl的屬性?
除了更改DataSource屬性的值外,網格的XAML與直接使用時的效果完全一樣。
我添加了TextBlock只是看我是否可以綁定任何東西。 我確實在那里找到NaN
。
<Style x:Key="HistoryPopupContentStyle" TargetType="ContentControl">
<Setter Property="ContentTemplate">
<Setter.Value>
<DataTemplate>
<StackPanel Orientation="Vertical">
<TextBlock Text="{TemplateBinding Width,
diag:PresentationTraceSources.TraceLevel=High}"
Background="White"
Foreground="Black"/>
<dxg:GridControl
DataSource="{Binding RelativeSource={RelativeSource
Path=DataContext,
TraceLevel=High}"
VerticalAlignment="Stretch"
HorizontalAlignment="Stretch"
>
<!-- Columns. The grid displays column headers
as desired but with no rows -->
</dxg:GridControl.Columns>
</dxg:GridControl>
</StackPanel>
</DataTemplate>
</Setter.Value>
</Setter>
</Style>
<Popup
Name="PopHistory"
DataContext="{Binding Path=HistoryList}"
>
<ContentControl DataContext="{Binding Path=HistoryList}"
Style="{StaticResource HistoryPopupContentStyle}"
Name="Testing"
/>
</Popup>
您將需要子類化ContentControl
(或者只是Control
),以便可以添加新的依賴項屬性。
public class GridControl : ContentControl
{
// TODO add dependency properties
public GridControl()
{
DefaultStyleKey = typeof(GridControl);
}
}
將“項目”依賴項屬性添加到上述控件中(類型IEnumerable
)。
接下來,更新您的模板以定位新類型:
<Style x:Key="HistoryPopupContentStyle" TargetType="local:GridControl">
<Setter Property="ContentTemplate">
<Setter.Value>
<DataTemplate>
<dxg:GridControl ItemsSource="{Binding RelativeSource={RelativeSource AncestorType=local:GridControl},Path=Items}" />
或者,您可以設置“模板”而不是“ ContentTemplate”。 這將是當您使用TemplateBinding
:
<Style x:Key="HistoryPopupContentStyle" TargetType="local:GridControl">
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="local:GridControl">
<dxg:GridControl ItemsSource="{TemplateBinding Items}" />
通過將Items
屬性綁定到源項目來使用它:
<local:GridControl Style="{StaticResource HistoryPopupContentStyle}"
Items="{Binding Path=HistoryList}" />
您也可以完全跳過創建子類,而僅使用ContentControl
的Content
屬性存儲項:
<Style x:Key="HistoryPopupContentStyle" TargetType="ContentControl">
<Setter Property="ContentTemplate">
<Setter.Value>
<DataTemplate>
<dxg:GridControl ItemsSource="{Binding RelativeSource={RelativeSource AncestorType=local:GridControl},Path=Content}" />
或使用Template / TemplateBinding方法
<Style x:Key="HistoryPopupContentStyle" TargetType="ContentControl">
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="ContentControl">
<dxg:GridControl ItemsSource="{TemplateBinding Content}" />
像這樣使用:
<ContentControl Style="{StaticResource HistoryPopupContentStyle}"
Content="{Binding Path=HistoryList}" />
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.