C# 绑定到viewmodel不起作用
我有一个名为C# 绑定到viewmodel不起作用,c#,wpf,C#,Wpf,我有一个名为ChannelControls的用户控件,它在另一个名为CMiX的控件中实例化了6次。我想将一个ChannelControls属性绑定到一个名为cmixdata的单例类 datacontext是在XAML中设置的: <UserControl x:Class="CMiX.CMiX_UI" DataContext="{x:Static CMiX:CMiXData.Instance}" ChannelControls名为ChannelSpriteCo
ChannelControls
的用户控件,它在另一个名为CMiX的控件中实例化了6次。我想将一个ChannelControls
属性绑定到一个名为cmixdata的单例类
datacontext是在XAML中设置的:
<UserControl
x:Class="CMiX.CMiX_UI"
DataContext="{x:Static CMiX:CMiXData.Instance}"
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");
}
}
}
尽管所有类都实现INotifyPropertyChange,但当ChannelSpriteCount
更改时,绑定不会在cmixdata中更新,它仍然是构造函数中设置的默认值…尝试以这种方式绑定
"{Binding Source={x:Static CMiXData.Instance}, Mode=TwoWay, Path=ChData[0].SpriteCount}"
UPD:正如@lecloneur所建议的那样,
Mode=TwoWay
是它工作所必需的。请不要忘记提及当前DataContext已设置为CMiXData.Instance
。您是否也在ChannelControl的XAML中的绑定上设置了Mode=TwoWay
?尝试将依赖项属性声明为SpriteCountProperty=DependencyProperty.Register(“ChannelSpriteCount”、typeof(string)、typeof(ChannelControls)、new FrameworkPropertyMetadata(null,FrameworkPropertyMetadata Options.AffectsRender,OnPriteCallChanged));然后看看它是否会在一个月内发生变化。幸运的是,它不起作用。singleton类未更新为新值。ChData[0]。SpriteCount不会触发其属性已更改。
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");
}
}
}
"{Binding Source={x:Static CMiXData.Instance}, Mode=TwoWay, Path=ChData[0].SpriteCount}"