XAML 根据屏幕分辨率选择视图

wd2eg0qa  于 2022-12-07  发布在  其他
关注(0)|答案(2)|浏览(169)

我有一个为特定分辨率的LCD显示器制作的WPF应用程序。WPF应用程序是固定大小的。视图通过DataTemplate绑定到其视图模型,如下所示:

<DataTemplate DataType="{x:Type vm:IdleViewModel}">
    <v:IdleView/>
</DataTemplate>

现在,我想让这个应用程序可用于第二个LCD显示器类型。视图将完全不同。有没有办法根据分辨率将视图模型绑定到不同的视图?

vlurs2pr

vlurs2pr1#

根据您的要求,有多种方法可以实现这一点。让我重点介绍两种可能适合您的不同方法。如何确定屏幕分辨率是另一个主题,请参阅:

数据模板选择器

您可以创建一个数据模板选择器,它根据屏幕分辨率返回DataTemplate。确定屏幕分辨率的机制来自上面的问题。

public class ResolutionDependentTemplateSelector : DataTemplateSelector
{
   public DataTemplate InvalidResolutionTemplate { get; set; }
   public DataTemplate Resolution1Template { get; set; }
   public DataTemplate Resolution2Template { get; set; }

   public override DataTemplate SelectTemplate(object item, DependencyObject container)
   {
      if (IsTargetResolution(480, 576))
         return Resolution1Template;

      if (IsTargetResolution(720, 480))
         return Resolution2Template;

      return InvalidResolutionTemplate;
   }

   private bool IsTargetResolution(double width, double height)
   {
      return Math.Abs(SystemParameters.PrimaryScreenWidth - width) < 1 &&
             Math.Abs(SystemParameters.PrimaryScreenHeight - height) < 1;
   }
}

您可以在XAML中指定此选择器。由于我不知道您使用的是哪个控件,因此本示例使用一个简单的ContentControl。要指定给它的属性可能会有所不同。

<ContentControl>
   <ContentControl.Resources>
      <DataTemplate x:Key="Resolution1Template">
         <!-- ...your markup. -->
      </DataTemplate>
      <DataTemplate x:Key="Resolution2Template">
         <!-- ...your markup. -->
      </DataTemplate>
   </ContentControl.Resources>
   <ContentControl.ContentTemplateSelector>
      <local:ResolutionDependentTemplateSelector Resolution1Template="{StaticResource Resolution1Template}"
                                                 Resolution2Template="{StaticResource Resolution2Template}"/>
   </ContentControl.ContentTemplateSelector>
</ContentControl>

资源字典

您可以建立个别的资源字典,其中包含每个不同屏幕的数据模板,沿着其他只适用于特定屏幕大小的特定资源。然后在启动时(例如,在AppOnStartup方法中),将符合屏幕分辨率的资源字典合并到应用程序资源(App.Resources)中。
根据应用程序的大小和复杂性,您可以将每个不同屏幕分辨率的控件分离到自己的项目中,类似于资源字典方法。如果应用程序总是在特定的LCD类型上运行,而从不在其他类型上运行,也可以为每个类型创建目标,这样每个 “平台” 就只包含它所需要的资源。

sgtfey8w

sgtfey8w2#

Is there any way to bind the view model to a different view depending the resolution?
Not using a single view model type and a corresponding DataTemplate alone.
You could either

  • Use two different view model types and views
  • Implement the view to adopt itself according to the view model (which should then know about the current screen resolution)
  • Use a DataTemplateSelector to select the appropriate view based on some logic other than just the type of the view model

相关问题