Question

I customize a MessageBox, in MessageBox.cs. In MainWindow, if click the button named Open Two MessageBox, then will start to run two BackgroundWorker respectively sleep 2000ms and 1000ms, and show the MessageBoxes. But you can find that:

enter image description here

the buttons in MessageBox1 goes into MessageBox2. I don't know why that?

These buttons are created and saveed in CtrlButtonCollection in MessageBoxModule.

I will go crazy by this problem.

Because of many code in the project, so I put it in GitHub.

The project in GitHub

Was it helpful?

Solution 2

You should always avoid initializing of reference types in default metadata of Dependency property. Since DP identifier registration is static, so this reference will be shared across all instances of MessageBox.

public static DependencyProperty CtrlButtonCollectionProperty =
            DependencyProperty.Register(
                "CtrlButtonCollection",
                typeof(IList<Button>),
                typeof(MessageBoxModule),
                new PropertyMetadata(new List<Button>())); <-- HERE

Use other overload where you don't need to pass default metadata or pass null which is default value for all reference types i.e. declare like this:

public static DependencyProperty CtrlButtonCollectionProperty =
            DependencyProperty.Register(
                "CtrlButtonCollection",
                typeof(IList<Button>),
                typeof(MessageBoxModule));

And do the initialization in its constructor:

public MessageBoxModule
{
    .....
    CtrlButtonCollectionProperty = new List<Button>();
    .....
}

OTHER TIPS

Your MessageBoxModule.CtrlButtonCollectionProperty is static and so, it'll only register once and you'll have the same List() for all the message boxes you'll create.

Use non-static DependencyProperty to solve this problem. (I'd also consider re-writing the whole thing).

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top