简体   繁体   中英

Different values in different instances of the same usercontrol in WPF

I am working on creating a map for an application, which I need to present in two different ways. One mini-map and one regular map, they are both made up of one single UserControl . My issue is that I am trying to find a smooth way of displaying the regular-sized map with area names, and the mini-map without. I have been looking into DependencyProperties as a possible way of doing this, or at least a way to illustrate my train of thought. What I have so far is this.

    public bool MiniMap
    {
        get { return (bool)GetValue(MiniMapProperty); }
        set { SetValue(MiniMapProperty, value); }
    }

    public static DependencyProperty MiniMapProperty =
        DependencyProperty.Register("MiniMap", 
        typeof(bool), 
        typeof(myMap), 
        new PropertyMetadata());

I then have all the TextBlocks with the right labels in the UserControl, and are currently trying to remove the Text property if the MiniMap property is set as true, and let them be if it is false. Currently I am just doing it on the title of the map, but I can loop through them all once I get this one to work.

    if (MiniMap == true)
        {
            this.Title.Text = "";
        }

I am then instantiating this UserControl in a different View twice, with the MiniMap property set as true in one case, and false in the other.

    <map:myMap x:Name="myMap" Visibility="Collapsed" MiniMap="False"/>
    <map:myMap x:Name="miniMap" Visibility="Visible" MiniMap="True"/>

The idea here is that once you click the Map button, the big map comes up (changes Visibility to Visible ) and since the MiniMap property is set to false in this instance, then TextBlock(s) should be empty, or removed preferably - but that is a different issue. My problem here tho is that no matter what I do both instances of my UserControl always seems to have the same value for the MiniMap property, so I can only turn the TextBlock either on in both cases, or off in both. Anyone have any idea how I can get this to work, or have another solution better suited for my problem?

Try to use a propertychanged callback

public static DependencyProperty MiniMapProperty =
    DependencyProperty.Register("MiniMap", 
    typeof(bool), 
    typeof(myMap), 
    new PropertyMetadata(new PropertyChangedCallback(OnMiniMapPropertyChanged)));


private static void OnMiniMapPropertyChanged(DependencyObject sender, DependencyPropertyChangedEventArgs e)
        {
            var control = sender as myMap;
            if (control != null && (bool)e.NewValue == true)
                control.Title.Text = "";
        }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM