user3666697
user3666697

Reputation: 313

Showing different controls programmatically

In my WPF app, I've to show different controls in the window for different user actions. Like, when user selects an image, I show a Image control and when the user selects a text file, I show a TextBox control. Similarly there are many controls for different user selections.

To do this I'm first doing Visibility = Visibility.Collapsed for all controls using a foreach loop, then doing Visibility = Visibility.Visible for the controls that I've to show.

Is there a more efficient way of doing this? The window flickers and is not really snappy when changing controls as there are many controls.

Upvotes: 0

Views: 70

Answers (2)

vidstige
vidstige

Reputation: 13077

I always use a ContentControl for this. It produces very clean xaml code and is superfast, I've never seen any flicker even in rather loaded views. It does require any extra frameworks beyond WPF.

<ContentControl Content="{Binding Selected}">
    <ContentControl.Resources>
        <DataTemplate DataType="{x:Type viewModels:FirstOne}">
            <!-- View code for first view goes here -->
            <TextBlock>Hi</TextBlock>
        </DataTemplate>
        <DataTemplate DataType="{x:Type viewModels:SecondOne}">
            <!-- View code for second view goes here -->
            <Image Source="{Binding Image}" />
        </DataTemplate>
    </ContentControl.Resources>
</ContentControl>

And then I have a MainViewModel handing the navigation with a property

class MainViewModel: ViewModel, INavigation
{
    public ViewModel Selected
    {
        get { return _selected; }
        private set
        {
            _selected = value;
            RaisePropertyChanged();
        }
        public void Show(ViewModel viewModel) { Selected = viewModel; }
    }
}

The INavigation interface is just something like so

interface INavigation { void Show(ViewModel viewModel); }

An example view model

class FirstOne: ViewModel
{
    private readonly INavigation _navigation;
    public FirstOne(INavigation navigation) { _navigation = navigation; }
    public void ButtonClicked()
    {
        _navigation.Show(new SecondOne());
    }
}

Upvotes: 2

Keith Frechette
Keith Frechette

Reputation: 91

First, you may want to avoid doing Visibility=Visibility.Collapsed for controls that you are about to make visible. That could reduce some unnecessary screen activity.

Second, rather than having the user experience all the individual visibility changes in a serial fashion, you might want to keep your controls in a parent control that you can hide before the visibility changes take place and then unhide once the changes are complete. You could even use an opacity animation to fade it out and then back in. Of course, without seeing or understanding more about your app, I can't tell what's really appropriate.

Upvotes: 0

Related Questions