當你在Flyout
內容數據綁定,綁定源是頁,並結合目標是PopupRoot
,他們有不同的DataContext
,所以不能在這裏工作。
此外,一個Flyout
控制是這樣的:
如果你把一個Border
爲Flyout
內容,它將被放置在ScrollContentPresenter
:
由於你可以看到,如果你設置了Width
和Height
的內容,它不會影響Flyout
的大小,因爲它內部有一個ScrollViewer
:ScrollViewer
的內容具有無限的高度和寬度。
我想我的彈出按鈕的寬度和高度結合與其他一些控制,但它不工作
因此,定製的Flyout
大小樣式的FlyoutPresenter
例如像這樣的正確方法:
<Flyout>
<Flyout.FlyoutPresenterStyle>
<Style TargetType="FlyoutPresenter">
<Setter Property="MinHeight" Value="100" />
<Setter Property="MinWidth" Value="100" />
</Style>
</Flyout.FlyoutPresenterStyle>
<Border Name="flyoutBorder" VerticalAlignment="Stretch" HorizontalAlignment="Stretch">
</Border>
</Flyout>
在這裏,我們需要使用MinHeight
和MinWidth
設置的Flyout
大小,但因爲你要綁定Width
和Height
到某些其他控件,並且Windows運行時不支持Setter的綁定用法。值(Binding不會評估並且Setter沒有效果,您不會收到錯誤,但不會得到錯誤要麼結果)。
通常在Setter.Value
需要數據綁定時,我們可以創建一些附加的依賴屬性。而要解決不同DataContext
問題,我們需要定義背後或例如視圖模型像這樣的代碼屬性:
public static double NewWidth { get; set; } = 100.0;
那麼這個屬性綁定到Width
popupBorder
的:
<Grid>
<Popup IsOpen="False" Name="popup">
<Grid Name="popupBorder" Background="Red" Height="100" Width="{Binding NewWidth}">
</Grid>
</Popup>
<Button Content="check flyout" Name="btn" Click="Button_Click" Foreground="Black">
<Button.Flyout>
<Flyout>
<Flyout.FlyoutPresenterStyle>
<Style TargetType="FlyoutPresenter">
<Setter Property="local:BindingBuilder.FlyoutWidth" Value="400" /> <!--This value has no meaning here, you can set it to any value.-->
<Setter Property="MinHeight" Value="100" />
</Style>
</Flyout.FlyoutPresenterStyle>
<Border Name="flyoutBorder" VerticalAlignment="Stretch" HorizontalAlignment="Stretch">
</Border>
</Flyout>
</Button.Flyout>
</Button>
</Grid>
要註冊附屬財產,你可以例如這樣的代碼:
public class BindingBuilder : DependencyObject
{
public static readonly DependencyProperty FlyoutWidthProperty =
DependencyProperty.RegisterAttached("FlyoutWidth", typeof(double), typeof(BindingBuilder), new PropertyMetadata(0, OnFlyoutWidthChanged));
public static double GetFlyoutWidth(DependencyObject obj)
{
return (double)obj.GetValue(FlyoutWidthProperty);
}
public static void SetFlyoutWidth(DependencyObject obj, double value)
{
obj.SetValue(FlyoutWidthProperty, value);
}
public static void OnFlyoutWidthChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
{
double newFlyoutWidth = (double)d.GetValue(FlyoutWidthProperty);
var presenter = (FlyoutPresenter)d;
presenter.MinWidth = MainPageViewModel.NewWidth;
}
}
這裏我只附上MinWidth
屬性,您還可以使用相同的方法來定製MinHeight
的FlyoutPresenter
。
只需要注意,設置'UpdateSourceTrigger = PropertyChanged'在單向綁定中不起作用。指定'Mode = OneWay'也是多餘的,因爲無論如何這是默認值。除此之外,你是否嘗試綁定popupBorder的ActualWidth和ActualHeight? – Clemens
是的我也試過,我也必須綁定,但只是在那不工作多數民衆贊成爲什麼我想到約束寬度和高度第一 –
localContext這裏是頁面的名稱。 NAME = 「localContext」。 –