【发布时间】:2018-03-11 05:11:54
【问题描述】:
在我的应用程序中,我在主窗口中使用了一个名为“ChannelControls”的usercontrol,我实例化了 6 次。
public partial class ChannelControls : UserControl
{
CMiXData cmixdata = CMiXData.Instance;
public ChannelControls()
{
InitializeComponent();
this.DataContext = this;
}
public static readonly DependencyProperty ChannelSpriteCountProperty =
DependencyProperty.Register("ChannelSpriteCount", typeof(string), typeof(ChannelControls), new PropertyMetadata("1"));
[Bindable(true)]
public string ChannelSpriteCount
{
get { return (string)this.GetValue(ChannelSpriteCountProperty); }
set { this.SetValue(ChannelSpriteCountProperty, value); }
}
我正在使用一个名为 cmixdata 的自定义类来保存我的应用程序的所有数据(它将包含 List 的字符串、双精度等的不同属性......)。 ChannelControls 将包含许多滑块、按钮和其他用户控件,但目前我正在尝试仅绑定其中一个。
这是这个自定义类的一部分,它将保存数据,它有一个私有构造函数,因为我需要从任何地方访问它:
[Serializable]
public class CMiXData : 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));
}
MessageBox.Show(propertyName);
}
private List<string> _SpriteCount = new List<string>(new string[] {"1", "1", "1", "1", "1", "1"});
public List<string> SpriteCount
{
get { return _SpriteCount; }
set
{
if(_SpriteCount != value)
{
_SpriteCount = value;
RaisePropertyChanged("SpriteCount");
}
}
}
下面是我尝试将 channelcontrol 属性 ChannelSpriteCount 绑定到我的单例类的方法:cmixdata。
<CMiX:ChannelControls x:Name="Layer0" Tag="0" Visibility="Visible" ChannelSpriteCount="{Binding SpriteCount[0], Mode=TwoWay}"/>
在ChannelControls 被实例化的主用户控件上,datacontext 是这样设置的:
public partial class CMiX_UI : UserControl
{
BeatSystem beatsystem = new BeatSystem();
CMiXData cmixdata = CMiXData.Instance;
public CMiX_UI()
{
InitializeComponent();
this.DataContext = cmixdata;
}
在 xaml 方面:
<UserControl
x:Class="CMiX.CMiX_UI"
DataContext="{x:Static CMiX:CMiXData.Instance}"
但由于某些原因,cmixdata 中的属性没有更新,始终具有默认值...
【问题讨论】:
-
CMiX:Counter和ChannelControls应该是同一个 UserControl 类吗? -
CMiX:Counter 在 ChannelControls 内
-
除了
UpdateSourceTrigger=PropertyChanged毫无意义之外,Binding 应该可以工作,因为您已将 ChannelControls 的 DataContext 设置为 CMiXData 的实例,并且该 DataContext 值应由子元素继承。您可以尝试在调用 InitializeComponent 之前设置 DataContext。 -
Counter.Count是什么类型的?