EzDevInfo.com

xaml interview questions

Top xaml frequently asked interview questions

Pan & Zoom Image

I want to create a simple image viewer in WPF that will enable the user to:

  • Pan (by mouse dragging the image).
  • Zoom (with a slider).
  • Show overlays (rectangle selection for example).
  • Show original image (with scroll bars if needed).

Can you explain how to do it?

I didn't find a good sample on the web. Should I use ViewBox? Or ImageBrush? Do I need ScrollViewer?

Thanks!


Source: (StackOverflow)

How to bind an enum to a combobox control in WPF?

I am trying to find a simple example where the enums are shown as is. All examples I have seen tries to add nice looking display strings but I don't want that complexity.

Basically I have a class that holds all the properties that I bind, by first setting the DataContext to this class, and then specifying the binding like this in the xaml file:

<ComboBox ItemsSource="{Binding Path=EffectStyle}"/>

But this doesn't show the enum values in the ComboBox as items.


Source: (StackOverflow)

Advertisements

How do I use WPF bindings with RelativeSource?

How do I use RelativeSource with WPF bindings and what are the different use-cases?


Source: (StackOverflow)

In WPF, what are the differences between the x:Name and Name attributes?

The title says it all. Sometimes it seems that the Name and x:Name attributes are interchangeable.

So, what are the definitive differences between them, and when is it preferable to use one over the other?

Are there any performance or memory implications to using them the wrong way?

EDIT Responses so far suggest that using x:Name all the time works fine, but I still want to know what the difference is. Microsoft put these two attributes into the very first release of WPF, so there must be some sensible explanation.


Source: (StackOverflow)

What's the difference between StaticResource and DynamicResource in WPF?

When using resources such as brushes, templates and styles in WPF, they can be specified either as StaticResources

<Rectangle Fill="{StaticResource MyBrush}" />

or as a DynamicResource

<ItemsControl ItemTemplate="{DynamicResource MyItemTemplate}"  />

Most of the times (always?), only one works and the other will throw exception during runtime. But I'd like to know why:

  • What is the main difference. Like memory or performance implications
  • Are there rules in WPF like "brushes are always static" and "templates are always dynamic" etc.?

I assume the choice between Static vs Dynamic isn't as arbitrary as it seems... but I fail to see the pattern.


Source: (StackOverflow)

Difference between SelectedItem, SelectedValue and SelectedValuePath

What is the difference betweeen the following:

All these dependency properties are defined in Selector class. I often confuse SelectedItem with SelectedValue , and SelectedValue with SelectedValuePath.

I would like to know the difference between them, and also when do we use them, especially SelectedValue and SelectedValuePath. Please explain their use with some simple examples.


Source: (StackOverflow)

How to get a ListBox ItemTemplate to stretch horizontally the full width of the ListBox?

I want to have the ListItems to extend with their orange background the full width of the Listbox.

Currently they are only as wide as the FirstName + LastName.

I've set every element I can to: HorizontalAlignment="Stretch".

I want the background of the ListboxItems to expand as the user stretches the Listbox so I don't want to put in absolute values.

What do I have to do so that the background color of the ListBoxItems fill the width of the ListBox?

<Window x:Class="TestListBoxSelectedItemStyle.Window1"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:local="clr-namespace:TestListBoxSelectedItemStyle"
    Title="Window1" Height="300" Width="300">

    <Window.Resources>
        <local:CustomerViewModel x:Key="TheDataProvider"/>

        <DataTemplate x:Key="CustomerItemTemplate">
            <Border CornerRadius="5" Background="Orange" HorizontalAlignment="Stretch" Padding="5" Margin="3">
                <StackPanel Orientation="Horizontal" HorizontalAlignment="Stretch" Width="Auto">
                    <TextBlock HorizontalAlignment="Stretch">
                    <TextBlock.Text>
                        <MultiBinding StringFormat="{}{0} {1}">
                            <Binding Path="FirstName"/>
                            <Binding Path="LastName"/>
                        </MultiBinding>
                    </TextBlock.Text>
                    </TextBlock>
                </StackPanel>
            </Border>
        </DataTemplate>

    </Window.Resources>

    <Grid>
        <ListBox ItemsSource="{Binding Path=GetAllCustomers, Source={StaticResource TheDataProvider}}"
                 ItemTemplate="{StaticResource CustomerItemTemplate}"/>
    </Grid>
</Window>

Source: (StackOverflow)

Newline in string attribute

How can I add a line break to text when it is being set as an attribute i.e.:

<TextBlock Text="Stuff on line1 \n Stuff on line2" />

Breaking it out into the exploded format isn't an option for my particular situation. What I need is some way to emulate the following:

<TextBlock>
  <TextBlock.Text>
    Stuff on line1 <LineBreak/>
    Stuff on line2
  </TextBlock.Text>
<TextBlock/>

Source: (StackOverflow)

ResourceDictionary in a separate assembly

I have resource dictionary files (MenuTemplate.xaml, ButtonTemplate.xaml, etc) that I want to use in multiple separate applications. I could add them to the applications' assemblies, but it's better if I compile these resources in one single assembly and have my applications reference it, right?

After the resource assembly is built, how can I reference it in the App.xaml of my applications? Currently I use ResourceDictionary.MergedDictionaries to merge the individual dictionary files. If I have them in an assembly, how can I reference them in xaml?


Source: (StackOverflow)

How to get StackPanel's children to fill maximum space downward?

I simply want flowing text on the left, and a help box on the right.

The help box should extend all the way to the bottom.

If you take out the outer StackPanel below it works great.

But for reasons of layout (I'm inserting UserControls dynamically) I need to have the wrapping StackPanel.

How do I get the GroupBox to extend down to the bottom of the StackPanel, as you can see I've tried:

  • VerticalAlignment="Stretch"
  • VerticalContentAlignment="Stretch"
  • Height="Auto"

XAML:

<Window x:Class="TestDynamic033.Test3"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    Title="Test3" Height="300" Width="600">
    <StackPanel 
        VerticalAlignment="Stretch" 
        Height="Auto">

        <DockPanel 
            HorizontalAlignment="Stretch" 
            VerticalAlignment="Stretch" 
            Height="Auto" 
            Margin="10">

            <GroupBox 
                DockPanel.Dock="Right" 
                Header="Help" 
                Width="100" 
                Background="Beige" 
                VerticalAlignment="Stretch" 
                VerticalContentAlignment="Stretch" 
                Height="Auto">
                <TextBlock Text="This is the help that is available on the news screen." TextWrapping="Wrap" />
            </GroupBox>

            <StackPanel DockPanel.Dock="Left" Margin="10" Width="Auto" HorizontalAlignment="Stretch">
                <TextBlock Text="Here is the news that should wrap around." TextWrapping="Wrap"/>
            </StackPanel>

        </DockPanel>
    </StackPanel>
</Window>

Answer:

Thanks Mark, using DockPanel instead of StackPanel cleared it up. In general, I find myself using DockPanel more and more now for WPF layouting, here's the fixed XAML:

<Window x:Class="TestDynamic033.Test3"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    Title="Test3" Height="300" Width="600" MinWidth="500" MinHeight="200">
    <DockPanel 
        VerticalAlignment="Stretch" 
        Height="Auto">

        <DockPanel 
            HorizontalAlignment="Stretch" 
            VerticalAlignment="Stretch" 
            Height="Auto" 
            MinWidth="400"
            Margin="10">

            <GroupBox 
                DockPanel.Dock="Right" 
                Header="Help" 
                Width="100" 
                VerticalAlignment="Stretch" 
                VerticalContentAlignment="Stretch" 
                Height="Auto">
                <Border CornerRadius="3" Background="Beige">
                    <TextBlock Text="This is the help that is available on the news screen." TextWrapping="Wrap" 

                Padding="5"/>
                </Border>
            </GroupBox>

            <StackPanel DockPanel.Dock="Left" Margin="10" Width="Auto" HorizontalAlignment="Stretch">
                <TextBlock Text="Here is the news that should wrap around." TextWrapping="Wrap"/>
            </StackPanel>

        </DockPanel>
    </DockPanel>
</Window>

Source: (StackOverflow)

How do I get a TextBox to only accept numeric input in WPF?

I'm looking to accept digits and the decimal point, but no sign.

I've looked at samples using the NumericUpDown control for WinForms, and this sample of a NumericUpDown custom control from Microsoft. But so far it seems like NumericUpDown (supported by WPF or not) is not going to provide the functionality that I want. The way my app is designed, nobody in their right mind is going to want to mess with the arrows. They don't make any practical sense, in the context of my app.

So I'm looking for a simple way to make a standard WPF TextBox accept only the characters that I want. Is this possible? Is it practical?

Thanks, SO!


Source: (StackOverflow)

Any way to make a WPF textblock selectable?

I want to make the text displayed in the Witty, an open source Twitter client, selectable. It is currently displayed using a custom textblock. I need to use a TextBlock because I'm working with the textblock's inlines to display and format the @username and links as hyperlinks. A frequent request is to be able to copy-paste the text. In order to do that I need to make the TextBlock selectable.

I tried to get it to work by displaying the text using a read-only TextBox styled to look like a textblock but this will not work in my case because a TextBox does not have inlines. In other words, I can't style or format the text within a TextBox individually like I can with a TextBlock.

Any ideas?


Source: (StackOverflow)

What is so special about Generic.xaml?

I've been trying to figure out how to organize my ResourceDictionary files for reuse and sharing with other members of my team.

I keep coming across "Generic.xaml", but if I look on MSDN for Generic.xaml or just do a Google search, I only seem to get blog posts and forum questions that happen to mention it--I can't seem to hit upon anything really authoritative and clear.

What is the difference between Generic.xaml and MyRandomlyNamedResourceDictionary.xaml? It seems like either way, I have to reference ResourceDictionaries stored in libraries with the Source attribute. E.g.,:

<Application.Resources>
    <ResourceDictionary
        Source="/CommonLibraryWpfThemes;component/Themes/Generic.xaml"
</Application.Resources>

So what advantage does Generic.xaml provide exactly? Does it have any purpose if I'm not trying to give my application multiple "looks" (i.e., if I have only one theme)?


Source: (StackOverflow)

DataTrigger where value is NOT null?

I know that I can make a setter that checks to see if a value is NULL and do something. Example:

<TextBlock>
  <TextBlock.Style>
    <Style>
      <Style.Triggers>
        <DataTrigger Binding="{Binding SomeField}" Value="{x:Null}">
          <Setter Property="TextBlock.Text" Value="It's NULL Baby!" />
        </DataTrigger>
      </Style.Triggers>
    </Style>
  </TextBlock.Style>
</TextBlock>

But how can I check for a "not" value... as in "NOT NULL", or "NOT = 3"? Is that possible in XAML?

Results: Thanks for your answers... I knew I could do a value converter (which means I would have to go in code, and that would not be pure XAML as I hoped for). However, that does answer the question that effectively "no" you can't do it in pure XAML. The answer selected, however, shows probably the best way to create that kind of functionality. Good find.


Source: (StackOverflow)

Binding to static property

I'm having a hard time binding a simple static string property to a text box.

Here's the class with the static property:

public class VersionManager
{
    private static string filterString;

    public static string FilterString
    {
        get { return filterString; }
        set { filterString = value; }
    }
}

In my xaml, I just want to bind this static property to a text box:

<TextBox>
    <TextBox.Text>
        <Binding Source="{x:Static local:VersionManager.FilterString}"/>
    </TextBox.Text>
</TextBox>

Everything compiles, but at run time, I get the following exception:

Cannot convert the value in attribute 'Source' to object of type 'System.Windows.Markup.StaticExtension'. Error at object 'System.Windows.Data.Binding' in markup file 'BurnDisk;component/selectversionpagefunction.xaml' Line 57 Position 29.

Any idea what I'm doing wrong?


Source: (StackOverflow)