如何在运行时将值从 window 传递给用户控件?

How to passing value from window to usercontrol at runtime?

这是我应该获取数据的用户控制代码:

这是我的主要 window,我在其中包含用户控件并将值设置为 属性:

这不起作用,因为该值始终为空。请帮助纠正我做错的任何事情。谢谢

据我所知,您似乎需要使用依赖项 属性。这将替换您拥有的 GetMyValue 属性。

查看此示例以了解自定义依赖项属性。

https://www.tutorialspoint.com/wpf/wpf_dependency_properties.htm

旁注:一个快速的方法是输入 "propdp" 然后按 Tab 键两次。然后按您的方式进行设置。

1.Make 请确保您已将范围设置为 'User' 而不是 'Admin',否则您将没有对资源的写入权限。 2.Make确定你有修改数据后保存的方法

用于写作 使用 Properties.Settings;

Settings.Default.myProperty = myValue;
Settings.Default.Save();

阅读

String myValue = Settings.Default["myProperty"].ToString();

您还可以通过 解决方案探索 > 你的项目 > 属性 > Settings.settings

一个很好的解决方案:

private void Window_Loaded(object sender, RoutedEventArgs e)
{
    var control = new UserControl1();
    control.GetMyValue = "HelloWorld";
    grid1.Childern.Add(control);
}

还有其他解决方案,例如Binding DataContext or making a custom DependencyProperty

UserControl 是在 GetMyValue 属性 设置之前创建的。您不能在创建实例之前设置实例的 属性...

等到 UserControl 加载完毕,您将获得预期的值:

public UserControl1()
{
    InitializeComponent();
    Loaded += (s, e) =>
    {
        string finalValue = GetMyValue;
    };
}

您需要创建依赖关系 属性。没有难事:

首先你需要注册:

public static readonly DependencyProperty GetMyValueProperty =
            DependencyProperty.Register("GetMyValue", typeof(string), 
            typeof(UserControl1), new UIPropertyMetadata(string.Empty));  

然后创建auto-属性:

public string GetMyValue
        {
            get { return (string )GetValue(GetMyValueProperty ); }
            set { SetValue(GetMyValueProperty , value); }
        }

就是这样,只需将此示例复制到您的 UserControl1 class。