【问题标题】:Bind to Window.Current.Bounds.Width in XAML绑定到 XAML 中的 Window.Current.Bounds.Width
【发布时间】:2012-11-20 04:46:55
【问题描述】:

我在 LayoutAware 页面上有一个弹出控件。

我真正想要的是让弹出窗口填满屏幕。

我认为解决方案是使用 Window.Current.Bounds.Height/Width 在弹出控件内部的网格上设置相应的属性。

我不想使用文件隐藏代码来设置这些属性。我希望能够绑定到 XAML 中的 Window.Current.Bounds.Height。

我可以这样做吗?

有没有更好的方法让弹出窗口填满屏幕?

【问题讨论】:

    标签: xaml microsoft-metro windows-runtime winrt-xaml


    【解决方案1】:

    您可以通过编写高度和宽度的转换器来做到这一点。

    public class WidthConverter : IValueConverter
    {
        public object Convert(object value, Type targetType, object parameter, string language)
        {
            return Window.Current.Bounds.Width;
        }
    
        public object ConvertBack(object value, Type targetType, object parameter, string language)
        {
            throw new NotImplementedException();
        }
    }
    
    public class HeightConverter : IValueConverter
    {
        public object Convert(object value, Type targetType, object parameter, string language)
        {
            return Window.Current.Bounds.Height;
        }
    
        public object ConvertBack(object value, Type targetType, object parameter, string language)
        {
            throw new NotImplementedException();
        }
    }
    

    将此添加到您的页面资源部分 -

        <common:WidthConverter x:Key="wc" />
        <common:HeightConverter x:Key="hc" />
    

    将它们用于您的弹出窗口 -

            <Popup x:Name="myPopup"  >
                <Grid  Background="#FFE5E5E5" Height="{Binding Converter={StaticResource hc}}" Width="{Binding Converter={StaticResource wc}}" />
            </Popup>
    

    【讨论】:

    • 我最终使用了这个解决方案。 @Typist 谢谢!
    • 这似乎没有响应页面大小的变化 -- 停靠到左侧或右侧,或事件 2/3 大小。
    【解决方案2】:

    您可以使用转换器(请参阅打字员) 或使用静态类。

    在您的 App.xaml 中:

    <datamodel:Foo x:Name="FooClass" />
    xmlns:datamodel="using:MyProject.Foo.DataModel"
    

    在你的 xaml 中:

    Source="{Binding Source={StaticResource FooClass}, Path=Width}"
    

    其中 Width 是您的类中返回 Window.Current.Bounds.Width 的属性。

    示例:public double Width{get{return Window.Current.Bounds.Width;}}

    问候。

    【讨论】:

    • 这也是一个很好的解决方案。如果我可以看到自己使用 5 或 6 个属性,我会创建一个静态类。 @大卫谢谢!
    • @罗伯特超级。如果它更好,你为什么不改变这个解决方案?
    • 我现在在我的项目中使用转换器,如上所示。这就是为什么我将替代答案标记为答案。您和打字员的答案都适用于我的情况。我在我的应用程序中使用 MVVM 模式。第三种解决方案是将它作为我的视图模型的属性。我不想为每个视图模型复制它。
    猜你喜欢
    • 1970-01-01
    • 2017-02-28
    • 2014-07-02
    • 1970-01-01
    • 2011-08-17
    • 2012-08-15
    • 2012-02-06
    • 2021-06-23
    • 1970-01-01
    相关资源
    最近更新 更多