保留对传递给UserControl的对象的引用 [英] Keep a reference to objects passed to a UserControl

查看:59
本文介绍了保留对传递给UserControl的对象的引用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我创建了一个具有ContentControl的UserControl.此ContentControl从正常的.xaml页获取Button.但是,根据某些事件,我需要更改此Button的Label或Image,但会收到NullReferenceException.

I created a UserControl that has a ContentControl in it. This ContentControl gets Buttons from the normal .xaml-pages. But depending on some events I need to change this Button's Label or Image but i am getting a NullReferenceException.

UserControl1.xaml

<Grid>
    <!-- different Stuff that needs to be around -->
    <ContentControl Content="{Binding UserControlContent, ElementName=userContent}"/>
</Grid>

UserControl1.xaml.cs

public static readonly DependencyProperty AppBarContentProperty =
    DependencyProperty.Register("UserControlContent", typeof(Grid), typeof(UserControl1), new PropertyMetadata(new Grid()));

public Grid UserControlContent
{
    get { return (Grid)GetValue(UserControlContentProperty); }
    set { SetValue(UserControlContentProperty, value); }
}

MainPage.xaml

<local:UserControl1>
    <local:UserControl1.UserControlContent>
        <Grid>
            <Controls:RoundButton x:Name="btn1"/>
        </Grid>
    </local:UserControl1.UserControlContent>
</local:UserControl1>

MainPage.xaml.cs

MainPage()
{
    btn1.Label = "new label";
}

使用UserControl内的按钮尝试此操作后,它就会失败.留在外面的按钮可以正常工作. 有什么更深层次的绑定可以保持对这些按钮的控制?

As soon as I try this with a button inside of the UserControl it fails. With buttons that stay outside it works. Is there any deeper binding possible to keep control of these buttons?

推荐答案

诀窍是使用mvvm绑定!

The trick is using the mvvm-binding!

该按钮的值现已绑定:

Label="{Binding RoundButtons[3].Label}"
Visibility="{Binding RoundButtons[3].VisibilityState, FallbackValue=Visible}"

这使我可以定义默认值,并且仍然可以随时更改它们,因为我需要更改它们.

This allows me to define default-values and still change them on the fly as I need them to be changed.

希望有人需要此信息;)

Hope someone needs this information ;)

这篇关于保留对传递给UserControl的对象的引用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆