【问题标题】:How to apply a style of a Button dynamically in WP 8.1?如何在 WP 8.1 中动态应用按钮样式?
【发布时间】:2015-06-09 06:28:55
【问题描述】:

我有一个 WP 8.1 应用程序。我正在遵循完整的 MVVM 设计模式。在 XAML 代码中

 <Grid>
    <Canvas x:Name="gameCanvas"         
         Width="{Binding CanvasWidth, 
                 Mode=TwoWay, 
                 UpdateSourceTrigger=PropertyChanged}">
         <ItemsControl ItemsSource="{Binding Path=ButtonItems, 
                             Mode=TwoWay,                            
                             UpdateSourceTrigger=PropertyChanged}">
      <ItemsControl.ItemTemplate>
         <DataTemplate x:Name="Dta">
             <Button x:Name="newsItemBtn"
                 Height="{Binding Height}"
                 Width="{Binding Width}"
                 Style="{StaticResource ButtonStyle2}"
                 Content="{Binding Content}"
                 Command="{Binding                       
                           Path=DataContext.ButtonClickCommand,
                           ElementName=gameCanvas}"
                           CommandParameter="{Binding Content}">
             </Button>
          </DataTemplate>
       </ItemsControl.ItemTemplate>
    </ItemsControl>
 </Canvas>

但我想要的是在运行时动态分配按钮的样式。 我在GamePage.XAML. 中定义了三个按钮样式

<Style x:Key="ButtonStyle1" />
<Style x:Key="ButtonStyle2" />
<Style x:Key="ButtonStyle3" />

现在基于ViewModel 上的某些值或某些属性,我想选择按钮样式 我尝试使用converter。但没有太大的成功。

知道如何实现这一目标吗?

【问题讨论】:

    标签: c# .net xaml mvvm windows-phone-8.1


    【解决方案1】:

    有一次我需要做同样的事情,我只是使用了一个转换器,它返回了一个命名资源:

    public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
    {
        if (value is bool && (bool)value)
        {
            return App.Current.Resources["ComplexProductTypeTemplate"];
        }
        return App.Current.Resources["SimpleProductTypeTemplate"];
    }
    

    我想它可以与键标识的资源以相同的方式工作。

    【讨论】:

    • 我在 XAML 中尝试过 Style="{Binding Path=DataContext.BtnStyle, Converter={StaticResource ButtonStyleConverter}}" 但它不起作用,
    • @Debhere - 你到底绑定了那个样式(我的意思是 BtnStyle 字段 - 那是什么)?另外,转换器本身会发生什么? ------> 编辑:好的,我刚刚查看了我是如何使用这些转换器的。您确定需要通过该“路径”属性绑定 BtnStyle 吗?
    • 是的,这是必需的,但是经过一些更改,现在我可以点击ButtonStyleConverterreturn App.Current.Resources["ButtonStyle3"]; 抛出未找到异常,我在调试中检查了资源,它不包含任何键,值为 Key.count = 0;
    • @Debhere - 是的,那个 Path 只是一种预感 - 我很少使用它,这是我能看到的唯一区别 :) 无论如何,我没有注意到你正在将样式添加到单个页面的资源。我们已将所有样式添加到应用程序的全局 ResourceDictionary,因此我可以在 App.Current.Resources 中找到它们。要使转换器为您工作,您必须以某种方式从属于您当前所在页面的资源中返回一些内容。或者只需将这三种样式添加到 App.xaml 中的 &lt;resources&gt; ;D
    • 太好了,这就是我想要的。它的工作,谢谢。在 App.xaml 中设置这些资源就可以了。
    猜你喜欢
    • 2016-12-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-03-02
    • 1970-01-01
    • 2021-07-20
    • 1970-01-01
    相关资源
    最近更新 更多