Keep a reference to objects passed to a UserControl

女生的网名这么多〃 提交于 2019-12-25 07:37:29

问题


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";
}

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?


回答1:


The trick is using the mvvm-binding!

The button's values are bound now:

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 ;)



来源:https://stackoverflow.com/questions/23077012/keep-a-reference-to-objects-passed-to-a-usercontrol

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!