【问题标题】:Binding Buttons' style to ViewModel property in WP7在 WP7 中将按钮的样式绑定到 ViewModel 属性
【发布时间】:2011-08-19 13:43:27
【问题描述】:

我在 AudioRecord 视图中有一个播放按钮。

目前它被定义为:

<Button Width="72" Height="72" Style="{StaticResource RoundPlay}" 
                DataContext="{Binding ElementName=this, Path=DataContext}"
                cmd:ButtonBaseExtensions.Command="{Binding PlayStopCommand}"
                />

当用户单击按钮时,项目 ViewModel 中的 PlayStopCommand 将被执行。我希望按钮在播放声音时将其样式设置为“RoundStop”。

如何将按钮的样式绑定到我的 ViewModel 中的属性(我应该使用什么属性类型),以便可以通过代码控制按钮的外观?

我定义了 RoundStop 样式,我只需要一种方法将其应用到代码中的按钮。

【问题讨论】:

    标签: c# silverlight windows-phone-7 mvvm styles


    【解决方案1】:

    您应该在视图模型中定义播放状态(播放/停止),并使用转换器将 Button.Style 绑定到该属性。在您的转换器中,根据当前状态返回不同的样式(取自 App.Current.Resources)。

    编辑:

    以下是您的转换器示例:

    public class StateStyleConverter : IValueConverter
    {
        public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
        {
            return (PlaybackState)value == PlaybackState.Playing ? App.Current.Resources["RoundPlay"] : App.Current.Resources["RoundStop"];
        }
    
        public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
        {
            throw new NotImplementedException();
        }
    }
    

    在本例中,PlaybackState 是一个枚举:

    public enum PlaybackState
    {
        Playing,
        Stopped
    }
    

    然后您应该将 state 属性添加到您的视图模型(通知更改的部分取决于您用于 MVVM 的框架):

    private PlaybackState state;
    public PlaybackState State
    {
        get { return state; }
        set
        {
            state = value;
            RaiseNotifyPropertyChanged("State");
        }
    }
    

    在 XAML 中声明您的转换器:

    <UserControl.Resources>
        <converters:StateStyleConverter x:Key="StateStyleConverter"/>
    </UserControl.Resources>
    

    最后绑定到按钮上:

    <Button Width="72" Height="72" Style="{Binding State, Converter={StaticResource StateStyleConverter}}" 
                DataContext="{Binding ElementName=this, Path=DataContext}"
                cmd:ButtonBaseExtensions.Command="{Binding PlayStopCommand}"
                />
    

    【讨论】:

    • 谢谢。如果您遇到一个示例,说明这是如何在演示项目中实现的,请像这里一样下载。谢谢。
    • 不客气!我编辑了这个问题并包含了一个关于如何做到这一点的例子。希望对您有所帮助。
    【解决方案2】:

    您可以使用ToggleButton 并在已选中/未选中的视觉状态中进行必要的视觉更改。

    如果您必须按照问题所述的方式进行操作,那么您可以在资源中定义样式,然后在 this.Resources["YourStyleKey"]; 的代码隐藏中访问它您的问题将来自视图模型的视图,因此我的第一个建议:)

    【讨论】:

    • 您能否解释一下“您的问题是将其从视图传递到视图模型”是什么意思。
    • 我的意思是,如果您开始将视图交给视图模型以便您可以访问资源,那么分离视图和视图模型的好处将会失效。我的意思是理想主义模式遵守意义上的“问题”:)
    • 我明白了。谢谢你。好吧,ToggleButton 是一个不同的控件。我定义了一个复杂的按钮模板,如果我切换到 ToggleButton,我不确定是否不必重新定义它的至少某些部分。我在 Blend 中看到了诸如“状态”之类的东西,我会尝试用它们“烹饪”一些东西。
    猜你喜欢
    • 2020-02-11
    • 2021-04-20
    • 1970-01-01
    • 1970-01-01
    • 2011-01-19
    • 2016-01-11
    • 1970-01-01
    • 2011-08-26
    • 2015-01-25
    相关资源
    最近更新 更多