c# - 为什么我在 XAML 中填充的通用列表在运行时为空?

标签 c# .net silverlight generics xaml

全部,

我有一个在自定义用户控件中定义的通用列表。

private List<string> m_AnimationNames = new List<string>();

public List<string> AnimationNames
        {
            get { return this.m_AnimationNames; }
            set { this.m_AnimationNames = value; }
        }

我在 xaml 中引用了这个列表,并像这样填充它。

<local:AnimatedCharacter.AnimationNames>
        <System:String>Walk</System:String>
        <System:String>Run</System:String>
        <System:String>Talk</System:String>
</local:AnimatedCharacter.AnimationNames>

然后,在调用 InitializeComponent() 并且列表始终返回大小为 0 且不包含任何元素后,我尝试在代码的其他地方引用此列表。

为什么这个列表在运行时是空的?当我在代码中访问它时,我错过了什么使这个列表计数为 0?

全类:

public partial class AnimatedCharacter : UserControl
    {

        private List<string> m_AnimationNames = new List<string>();



        public AnimatedCharacter()
        {
            InitializeComponent();                        
            DoSomething();
        }


        public List<string> AnimationNames
        {
            get { return this.m_AnimationNames; }
            set { this.m_AnimationNames = value; }
        }


        public void DoSomething(){
            Console.WriteLine("Anim: " + AnimationNames.Count);   
        }
    }
}

XAML 实例:

<local:AnimatedCharacter x:Name="ac_guy1" Height="315" Width="273" Canvas.Left="-666" Canvas.Top="-99" >            
            <local:AnimatedCharacter.AnimationNames>
                <System:String>Walk</System:String>
                <System:String>Run</System:String>
                <System:String>Talk</System:String>
            </local:AnimatedCharacter.AnimationNames>

</local:AnimatedCharacter>

最佳答案

控件加载后调用 DoSomething(等待 Loaded 事件)。在通过 XAML 设置 AnimationNames 属性之前,您在构造函数中调用它:

public AnimatedCharacter() 
{ 
    InitializeComponent();                         

    this.Loaded += new RoutedEventHandler(OnLoaded);
} 

private void OnLoaded(object sender, RoutedEventArgs e)
{
     this.DoSomething();
}

关于c# - 为什么我在 XAML 中填充的通用列表在运行时为空?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2276201/

相关文章:

c# - Silverlight 4 剪贴板安全异常 "access is not allowed"?

C# - 无法使用 Invoke() 从后台线程追加文本以进行控制

C# WPF listview不更新

.net - Watin CaptureWebPageToFile() 生成黑色图像

.net - 更改 MVVM 中的 View

c# - C#中对象的碰撞检测

c# - 更改 wpf 中堆栈面板的子索引

c# - 将类序列化为 xml

.net - 在 AWS .NET SDK 中找不到凭证

c# - 根据鼠标位置移动 wpf 按钮但它闪烁