【问题标题】:Binding to a static property in WinRT在 WinRT 中绑定到静态属性
【发布时间】:2014-06-29 11:12:56
【问题描述】:

我相信这是可能的,但我似乎无法让它发挥作用;这是我的视图模型:

namespace MyApp.ViewModel
{
    public class MainViewModel : INotifyPropertyChanged
    {
        private static MainViewModel _mvm;
        public static MainViewModel MVM()
        {
            if (_mvm == null)
                _mvm = new MainViewModel();

            return _mvm;
        }

        private string _imagePath = @"c:\location\image.png";
        public string ImagePath
        {
            get { return _imagePath; }
            set
            {
               SetProperty<string>(ref _imagePath, value); 
            }
        }

        public event PropertyChangedEventHandler PropertyChanged;

        protected bool SetProperty<T>(ref T storage, T value, [CallerMemberName] String propertyName = null)
        {
            if (Equals(storage, value)) return false;

            storage = value;
            OnPropertyChanged<T>(propertyName);
            return true;
        }

        private void OnPropertyChanged<T>([CallerMemberName]string caller = null)
        {
            var handler = PropertyChanged;
            if (handler != null)
            {
                handler(this, new PropertyChangedEventArgs(caller));
            }
        }
 ...

这是我的 App.xaml:

xmlns:vm="using:MyApp.ViewModel">

<Application.Resources>
    <ResourceDictionary>
        <vm:MainViewModel x:Key="MainViewModel"  />
    </ResourceDictionary>
</Application.Resources>

这是绑定:

<Page
 ...
    DataContext="{Binding MVM, Source={StaticResource MainViewModel}}">

    <StackPanel Orientation="Horizontal" Margin="20" Grid.Row="0">
        <TextBlock FontSize="30" Margin="10">Image</TextBlock>            
        <TextBox Text="{Binding ImagePath}" Margin="10"/>
    </StackPanel>
...

我似乎无法让绑定工作;我在这里错过了什么?我希望该字段使用默认值填充,但事实并非如此;我在 ViewModel 中设置了断点,但它没有中断。

【问题讨论】:

    标签: xaml mvvm binding windows-runtime winrt-xaml


    【解决方案1】:

    对我来说,您的绑定语法不正确。 DataContext="{Binding MVM, Source={StaticResource MainViewModel} 表示您的 MainViewModel 类中应该有一个“MVM”属性。在您的情况下,MVM 是一种方法。

    尝试用属性替换您的 MVM 方法。这可能行得通。

    另一种方法是设置

    DataContext="{StaticResource MainViewModel}"
    

    在那种情况下,MVM 方法将被废弃(我没有在 WinRT 上尝试过)

    【讨论】:

    • 我花了好几个小时看这个,从来没有注意到我将它声明为一个函数!谢谢。
    猜你喜欢
    • 2010-10-30
    • 2014-09-10
    • 2014-01-29
    • 1970-01-01
    • 2012-10-15
    • 2013-08-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多