绑定到viewmodel无法正常工作

时间:2017-09-30 15:42:16

标签: c# wpf

我有一个名为ChannelControls的用户控件,它在另一个名为CMiX的实例中被实例化了6次。我想将ChannelControls属性中的一个绑定到名为cmixdata的单例类。

datacontext在XAML中设置:

<UserControl
        x:Class="CMiX.CMiX_UI"
        DataContext="{x:Static CMiX:CMiXData.Instance}"

ChannelControls使用如下:

<CMiX:ChannelControls x:Name="Layer0" ChannelSpriteCount="{Binding ChData[0].SpriteCount,Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}"/>
名为ChannelControls

ChannelSpriteCount属性绑定到cmixdata类,其定义如下:

[Serializable]
public class CMiXData : DependencyObject, INotifyPropertyChanged
{
    private static CMiXData _instance = null;
    public static CMiXData Instance
    {
        get
        {
            if (_instance == null)
            {
                _instance = new CMiXData();
            }
            return _instance;
        }
    }
    private CMiXData() { } //prevent instantiation from outside the class


    public event PropertyChangedEventHandler PropertyChanged;
    private void RaisePropertyChanged(string propertyName)
    {
        var handler = PropertyChanged;
        if (handler != null)
        {
            handler(this, new PropertyChangedEventArgs(propertyName));
        }
    }

    private ObservableCollection<ChannelData> _ChData = new ObservableCollection<ChannelData>(new ChannelData[] { new ChannelData { SpriteCount = "1" }, new ChannelData { SpriteCount = "1" }, new ChannelData { SpriteCount = "1" }, new ChannelData { SpriteCount = "1" }, new ChannelData { SpriteCount = "1" }, new ChannelData { SpriteCount = "1" } });
    public ObservableCollection<ChannelData> ChData
    {
        get { return _ChData; }
        set
        {
            if (_ChData != value)
            {
                _ChData = value;
                RaisePropertyChanged("ChData");
            }
        }
    }

这是ChannelData类,它为我的应用程序中的每个ChannelControls实例保存数据:

public class ChannelData : INotifyPropertyChanged
{
    public ChannelData() { }

    public event PropertyChangedEventHandler PropertyChanged;
    private void RaisePropertyChanged(string propertyName)
    {
        var handler = PropertyChanged;
        if (handler != null)
        {
            handler(this, new PropertyChangedEventArgs(propertyName));
        }
    }

    private string _SpriteCount;
    public string SpriteCount
    {
        get { return _SpriteCount; }
        set
        {
            if (_SpriteCount != value)
            {
                _SpriteCount = value;
                RaisePropertyChanged("SpriteCount");
            }
        }
    }

尽管所有类都实现了INotifyPropertyChange,但当ChannelSpriteCount发生更改时,绑定不会在cmixdata中更新,它仍然是构造函数中设置的默认值...

1 个答案:

答案 0 :(得分:1)

尝试以这种方式绑定。

"{Binding Source={x:Static CMiXData.Instance}, Mode=TwoWay, Path=ChData[0].SpriteCount}"

UPD:正如@lecloneur建议Mode=TwoWay是必要的。