![](/img/trans.png)
[英]Setting the Maximum Height that a RowDefinition can take Xamarin App
[英]Setting the RowDefinition Height from StaticResource
在我的WPF樣式中,我已經定義了一個標准網格行高度,我想應用於幾個地方,如下所示:
<system:Double x:Key="TableRowHeight">22</system:Double>
但是,當我想這樣應用時,它不起作用:
<RowDefinition Height="{StaticResource TableRowHeight}"/>
相反,我需要創建一個完整的風格,如:
<Style x:Key="GridTableRow" TargetType="{x:Type RowDefinition}">
<!--<Setter Property="Height" Value="{StaticResource TableRowHeight}"/>-->
<Setter Property="Height" Value="22"/>
</Style>
從注釋掉的行中可以看出,嘗試引用Style定義中的數字常量也不起作用,但“硬編碼”值也可以。
現在我查了一下,我想這是因為與Height屬性相關聯的類型是GridLength,它在某種程度上無法在從另一個資源傳入時自動轉換double值...
問題是似乎沒有辦法從XAML創建GridLength對象。 價值屬於只讀。 所以像這樣的東西也不起作用:
<Style x:Key="GridTableRow" TargetType="{x:Type RowDefinition}">
<Setter Property="Height">
<Setter.Value>
<GridLength Value="{StaticResource TableRowHeight}"/>
</Setter.Value>
</Setter>
</Style>
有沒有辦法讓它工作,或者我應該忘記使用該常量,只使用帶有硬編碼值的RowDefinition樣式代替常量?
當您“硬編碼”值時,XAML處理器會查找可以將其從字符串轉換為必要類型的轉換器。 甚至你的TableRowHeight
資源也在使用DoubleConverter來創建。 GridLength
使用GridLengthConverter 。
因此編譯器中沒有自動轉換/轉換 - WPF需要顯式查找類並調用convert方法。 在StaticResource
的情況下,它會跳過此步驟。
綁定確實使用類型轉換器,因此以下方法可以按預期工作:
<RowDefinition Height="{Binding Source={StaticResource TableRowHeight}}" />
這是有效的,因為GridLengthConverter
知道如何從Double
轉換。 但是,在您的情況下,這不應該是必要的。 如果以初始化Double
(在標記內)的方式初始化GridLength
資源,則將在分配資源之前調用字符串轉換:
<GridLength x:Key="TableRowHeight">22</GridLength>
然后你就可以直接調用資源了。
試試這個:
<Window
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="MainWindow" Height="350" Width="525"
xmlns:t="clr-namespace:System.Windows;assembly=PresentationFramework">
<Window.Resources>
<t:GridLength x:Key="gridHeight">50</t:GridLength>
</Window.Resources>
<Grid>
<Grid.RowDefinitions>
<RowDefinition Height="{StaticResource gridHeight}"></RowDefinition>
</Grid.RowDefinitions>
....
您必須創建GridLength
類型的資源才能應用為RowDefinition.Height
的類型為GridLength
:
<window:GridLength x:Key="TableRowHeight">50</window:GridLength>
無論如何,這將適用於您想要應用它。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.