C# WPF - TransitioningContentControl with App.content - c#

I Work with the theme of MahApps (Metro Dark) I looked the animations of this theme.
I came to a dead end: indeed I created a system to switch between different UserControl, that is to say that I have only one window and clicking on different buttons, I have this or such UserControl. But now I am with this system switch, I have no animation (only the start of the application).
How can I make an animation for each change in UserControl (Keeping Metro theme)?
Somebody ask me : use TransitioningContentControl
But i made my switcher like this :
class Switcher
{
public static UserControl WClient;
public static UserControl WHome;
public static UserControl WDataBase;
public Switcher()
{
WClient = new Windows.Client();
WHome = new Windows.Home();
WDataBase = new Windows.DataBase();
}
public static void currentWindow(UserControl window, string color)
{
Window curApp = Application.Current.MainWindow;
curApp.Content = window;
if (window == WClient)
{
curApp.Title = "CLIENT - INFO-TOOLS - BY NAOGRAFIX";
}
else if (window == WDataBase)
{
curApp.Title = "DATABASE - INFO-TOOLS - BY NAOGRAFIX";
}
else
{
curApp.Title = "HOME - INFO-TOOLS - BY NAOGRAFIX";
}
currentColor(color);
}
}
Now, when i clic on a button (to switch userControl) i use this :
private void BtnDataBase_Click(object sender, RoutedEventArgs e)
{
var color = "Red";
if (DataBase.isConnected) { color = "Green"; }
Switcher.currentWindow(Switcher.WDataBase, color);
}
I use CONTENT, i dont know if i can use TransitioningContentControl
Help :)
Nao*

You do need to use transitioning content control as you have said. You can add that as the direct content of the window then access it by name from the mainwindow and change its content instead.
Xaml
<metro:TransitioningContentControl x:Name="tContent"/>
C#
((ContentControl)curApp.FindName("tContent")).Content = window;
You will need the xml namespace definition
xmlns:metro="clr-namespace:MahApps.Metro.Controls;assembly=MahApps.Metro"
and you can change the transition using the Transition property on TransitioningContentControl

WPF XAML below shows use of MahApps.Metro TransitioningContentControl.
Click on the Content listbox to switch content.
Select the transition effect in the Transition listbox, then change selected Content to see the effect.
<Window x:Class="WpfMahApp.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:mah="http://metro.mahapps.com/winfx/xaml/controls"
mc:Ignorable="d"
Title="MainWindow" Height="600" Width="800">
<Window.Resources>
<TextBlock x:Key="Content1" Width="400" Height="200" Text="Content 1: TextBox" Background="Aqua" />
<Canvas x:Key="Content2" Width="200" Height="400" Background="DarkOrange">
<Ellipse Fill="YellowGreen" Stroke="Black" Width="100" Height="200" />
<Label Content="Content2: Canvas" />
</Canvas>
<Border x:Key="Content3" Width="100" Height="100" Background="Yellow" BorderBrush="Blue" BorderThickness="2" CornerRadius="4">
<TextBlock Text="Content3: Border" />
</Border>
</Window.Resources>
<StackPanel Orientation="Horizontal">
<StackPanel Orientation="Vertical" >
<CheckBox Margin="4" Content="Is Transitioning" IsChecked="{Binding ElementName=TransitioningContentControl,Path=IsTransitioning , Mode=OneWay}" />
<StackPanel Orientation="Vertical" Margin="8">
<TextBlock Text="Content" FontWeight="Bold"/>
<ListBox Name="ContentSelection" HorizontalAlignment="Left">
<ListBoxItem Content="Content 1" Tag="{StaticResource Content1}" />
<ListBoxItem Content="Content 2" Tag="{StaticResource Content2}" />
<ListBoxItem Content="Content 3" Tag="{StaticResource Content3}" />
</ListBox>
</StackPanel>
<StackPanel Orientation="Vertical" Margin="8">
<TextBlock Text="Transition" FontWeight="Bold" />
<ListBox Name="Transition" HorizontalAlignment="Left">
<ListBoxItem Content="Default" Tag="{x:Static mah:TransitionType.Default}"/>
<ListBoxItem Content="Normal" Tag="{x:Static mah:TransitionType.Normal}"/>
<ListBoxItem Content="Up" Tag="{x:Static mah:TransitionType.Up}"/>
<ListBoxItem Content="Down" Tag="{x:Static mah:TransitionType.Down}"/>
<ListBoxItem Content="Left" Tag="{x:Static mah:TransitionType.Left}" />
<ListBoxItem Content="Right" Tag="{x:Static mah:TransitionType.Right}"/>
<ListBoxItem Content="LeftReplace" Tag="{x:Static mah:TransitionType.LeftReplace}"/>
<ListBoxItem Content="RightReplace" Tag="{x:Static mah:TransitionType.RightReplace}"/>
</ListBox>
</StackPanel>
</StackPanel>
<mah:TransitioningContentControl Margin="8"
Name="TransitioningContentControl"
Background="Beige" BorderBrush="Black" BorderThickness="1"
Content="{Binding ElementName=ContentSelection, Path=SelectedValue.Tag}"
Transition="{Binding ElementName=Transition, Path=SelectedValue.Tag}" />
</StackPanel>
</Window>

Related

Change the background of the button that is used as a TabItem Header

I using code from a tutorial to develop a GUI with Tab Menu in WPF. Here, the buttons act as the Tab Menu header and every button is linked with an id. Based on the user selection, the id changes which in turn triggers what is displayed when a particular button is clicked. I want to change the background of the button, if it is selected. How can this be done?
Following is the xaml code:
<StackPanel Background="WhiteSmoke">
<Grid Height="40">
<StackPanel HorizontalAlignment="Left" Margin="20 0">
<ComboBox FontSize="15" Width="50" Foreground="#FFA2A2A2" SelectedIndex="0" VerticalAlignment="Center">
<ComboBoxItem Content="EN"/>
</ComboBox>
</StackPanel>
<StackPanel Orientation="Horizontal" HorizontalAlignment="Right" Margin="20 0">
<Button Content="FAQ" Background="{x:Null}" BorderBrush="{x:Null}" Foreground="#FFA2A2A2" FontSize="15" FontWeight="Bold" VerticalAlignment="Center"/>
<Button Content="CONTACT" Background="{x:Null}" BorderBrush="{x:Null}" Foreground="#FFA2A2A2" FontSize="15" FontWeight="Bold" VerticalAlignment="Center"/>
<Button Content="ORDER STATUS" Background="{x:Null}" BorderBrush="{x:Null}" Foreground="#FFA2A2A2" FontSize="15" FontWeight="Bold" VerticalAlignment="Center"/>
<Button Content="MY ACCOUNT" Background="{x:Null}" BorderBrush="{x:Null}" Foreground="#FFA2A2A2" FontSize="15" FontWeight="Bold" VerticalAlignment="Center"/>
</StackPanel>
</Grid>
<Grid Height="100">
<StackPanel Orientation="Horizontal" VerticalAlignment="Top" Margin="10 0">
<Button x:Name="b1" Uid="0" Width="150" Content="HOME" Height="50" Background="{x:Null}" BorderBrush="{x:Null}" Foreground="#FF2196F3" Click="Button_Click"/>
<Button Uid="1" Width="150" Content="SHOP" Height="50" Background="{x:Null}" BorderBrush="{x:Null}" Foreground="#FF2196F3" Click="Button_Click"/>
<Button Uid="2" Width="150" Content="BLOG" Height="50" Background="{x:Null}" BorderBrush="{x:Null}" Foreground="#FF2196F3" Click="Button_Click"/>
<Button Uid="3" Width="150" Content="PAGES" Height="50" Background="{x:Null}" BorderBrush="{x:Null}" Foreground="#FF2196F3" Click="Button_Click"/>
<Button Uid="4" Width="150" Content="PRODUCTS" Height="50" Background="{x:Null}" BorderBrush="{x:Null}" Foreground="#FF2196F3" Click="Button_Click"/>
<Button Uid="5" Width="150" Content="BRANDS" Height="50" Background="{x:Null}" BorderBrush="{x:Null}" Foreground="#FF2196F3" Click="Button_Click"/>
<Button Uid="6" Width="150" Content="GIFT CARDS" Height="50" Background="{x:Null}" BorderBrush="{x:Null}" Foreground="#FF2196F3" Click="Button_Click"/>
</StackPanel>
<Grid x:Name="GridCursor" Width="150" Height="5" Background="#FF2196F3" HorizontalAlignment="Left" Margin="10 0"/>
</Grid>
<Grid x:Name="GridMain" Height="460" Background="Aquamarine">
</Grid>
</StackPanel>
Following is the code behind:
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
}
private void Button_Click(object sender, RoutedEventArgs e)
{
int index = int.Parse(((Button)e.Source).Uid);
GridCursor.Margin = new Thickness(10 + (150 * index), 0, 0, 0);
switch (index)
{
case 0:
GridMain.Background = Brushes.Aquamarine;
b1.Background = Brushes.Yellow;
break;
case 1:
GridMain.Background = Brushes.Beige;
break;
case 2:
GridMain.Background = Brushes.CadetBlue;
break;
case 3:
GridMain.Background = Brushes.DarkBlue;
break;
case 4:
GridMain.Background = Brushes.Firebrick;
break;
case 5:
GridMain.Background = Brushes.Gainsboro;
break;
case 6:
GridMain.Background = Brushes.HotPink;
break;
}
}
I am able to change the background if the button is selected using b1.Background = Brushes.Yellow; . However, the background doesn't change to default when a different button is selected. Also, I am not able to set the background of the button (Uid =1) with which the GUI is launched.
I'm using the community toolkit mvvm for this sample below. I'm not sure this does exactly what you're asking but the binding and templating demonstrates the mvvm approach.
My mainwindow - no buttons.
<Window.DataContext>
<local:MainWindowViewModel/>
</Window.DataContext>
<Grid>
<Grid.RowDefinitions>
<RowDefinition Height="Auto"/>
<RowDefinition Height="*"/>
</Grid.RowDefinitions>
<ListBox ItemsSource="{Binding Choices}"
x:Name="lb"
>
<ListBox.ItemsPanel>
<ItemsPanelTemplate>
<StackPanel Orientation="Horizontal"/>
</ItemsPanelTemplate>
</ListBox.ItemsPanel>
<ListBox.ItemTemplate>
<DataTemplate>
<Grid Width="160">
<Grid.RowDefinitions>
<RowDefinition Height="22"/>
<RowDefinition Height="12"/>
</Grid.RowDefinitions>
<Rectangle Fill="Yellow">
<Rectangle.Style>
<Style TargetType="Rectangle">
<Setter Property="Visibility" Value="Collapsed"/>
<Style.Triggers>
<DataTrigger
Binding="{Binding RelativeSource={RelativeSource
Mode=FindAncestor,
AncestorType={x:Type ListBoxItem}},
Path=IsSelected}"
Value="True">
<Setter Property="Visibility" Value="Visible"/>
</DataTrigger>
</Style.Triggers>
</Style>
</Rectangle.Style>
</Rectangle>
<TextBlock Text="{Binding Description}"
TextAlignment="Center"
/>
<Border Grid.Row="1"
CornerRadius="10"
>
<Border.Background>
<SolidColorBrush Color="{Binding BackgroundBrushName}"/>
</Border.Background>
</Border>
</Grid>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
<Rectangle Grid.Row="1">
<Rectangle.Fill>
<SolidColorBrush Color="{Binding SelectedItem.BackgroundBrushName, ElementName=lb}"/>
</Rectangle.Fill>
</Rectangle>
</Grid>
</Window>
Mainwindowviewmodel
public partial class MainWindowViewModel : ObservableObject
{
public List<Choice> Choices { get; set; } = new List<Choice>
{
new Choice{ Description = "Shop", BackgroundBrushName = "Red"},
new Choice{ Description = "Blog", BackgroundBrushName = "Blue"},
new Choice{ Description = "Products", BackgroundBrushName = "Green"}
};
}
Choice
public partial class Choice : ObservableObject
{
public string BackgroundBrushName { get; set; }
[ObservableProperty]
private string description = string.Empty;
}
None of those properties change but you should always implement inotifypropertychanged on any viewmodel and ObservableObject adds that. description does not change so it doesn't really need change notification but I thought it would be interesting to see the code generator creates a Description property for you.
The collection is templated out into UI. The "menu" is a horizontal listbox which has the selector behaviour so you can click one and it is selected.
The background for the selected choice is usually visibility collapsed but a datatrigger sets it to visible if it's in the selected item.
We could also bind selecteditem mode=twoway and set that to the first choice if we wanted an initial one....errm... chosen.
Hopefully this gives you a reasonably beginner friendly introduction to mvvm techniques.

How to control visibility of view inside Master items in MasterDetailsView

I'm looking for a way to handle the visibility of nested items in a list for MasterDetailsView. Is there a way I can use the ShowButton boolean I created to control the visibility of an item (more button - with an ellipsis) within the list items used in my MasterDetailsView? Would I need to use dependency properties in this case or should something else be used?
Expected result
Current result
XAML
<Page
x:Class="MD.MainPage"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="using:MD"
xmlns:controls="using:Microsoft.Toolkit.Uwp.UI.Controls"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
mc:Ignorable="d">
<Grid>
<controls:MasterDetailsView x:Name="MyMasterDetailsView"
BackButtonBehavior="Automatic"
ItemsSource="{x:Bind Emails}"
NoSelectionContent="Select an item to view"
CompactModeThresholdWidth="720">
<controls:MasterDetailsView.ItemTemplate>
<DataTemplate>
<Grid>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="*"/>
<ColumnDefinition Width="Auto"/>
</Grid.ColumnDefinitions>
<StackPanel Grid.Column="0" Margin="0,8">
<TextBlock Text="{Binding From}"
Style="{ThemeResource SubtitleTextBlockStyle}"/>
<TextBlock Text="{Binding Body}"
Style="{ThemeResource BodyTextBlockStyle}"
Opacity=".6"/>
</StackPanel>
<Button Grid.Column="1"
x:Name="MoreBtn"
Background="Transparent"
Content=""
FontFamily="Segoe MDL2 Assets"
HorizontalAlignment="Right"
VerticalAlignment="Top"
Margin="10"
Padding="10"
Click="MoreBtn_Click"/>
</Grid>
</DataTemplate>
</controls:MasterDetailsView.ItemTemplate>
<controls:MasterDetailsView.DetailsTemplate>
<DataTemplate>
<RelativePanel Margin="24">
<TextBlock Text="{Binding From}"
Style="{ThemeResource SubtitleTextBlockStyle}"
Margin="12,-6,0,0"/>
<TextBlock x:Name="Body"
Text="{Binding Body}"
Style="{ThemeResource BodyTextBlockStyle}"
TextWrapping="Wrap"
Margin="0,12,0,0"/>
</RelativePanel>
</DataTemplate>
</controls:MasterDetailsView.DetailsTemplate>
<controls:MasterDetailsView.NoSelectionContentTemplate>
<DataTemplate>
<StackPanel HorizontalAlignment="Center"
VerticalAlignment="Center">
<SymbolIcon Symbol="Mail"
RenderTransformOrigin=".5,.5">
<SymbolIcon.RenderTransform>
<CompositeTransform
ScaleX="2"
ScaleY="2"/>
</SymbolIcon.RenderTransform>
</SymbolIcon>
<TextBlock Text="{Binding}"
FontSize="24"
Margin="0,12"/>
</StackPanel>
</DataTemplate>
</controls:MasterDetailsView.NoSelectionContentTemplate>
<controls:MasterDetailsView.MasterCommandBar>
<CommandBar>
<AppBarButton Icon="Back" Label="Back"/>
<AppBarButton Icon="Forward" Label="Forward"/>
<CommandBar.Content>
<TextBlock Margin="12,14">
<Run Text="{Binding Emails.Count}" />
<Run Text="Items" />
</TextBlock>
</CommandBar.Content>
</CommandBar>
</controls:MasterDetailsView.MasterCommandBar>
<controls:MasterDetailsView.DetailsCommandBar>
<CommandBar>
<AppBarButton Icon="MailReply" Label="Reply" />
<AppBarButton Icon="MailReplyAll" Label="Reply All" />
<AppBarButton Icon="MailForward" Label="Forward" />
</CommandBar>
</controls:MasterDetailsView.DetailsCommandBar>
</controls:MasterDetailsView>
</Grid>
</Page>
Item class (Email)
public class Email
{
public string From { get; set; }
public string Body { get; set; }
public bool ShowButton { get; set; }
}
public class MyEmailManager
{
public static List<Email> GetEmails()
{
var MyEmails = new List<Email>
{
new Email
{
From = "Steve Johnson",
Body = "Are you available for lunch tomorrow? A client would like to discuss a project with you.",
ShowButton = true
},
new Email
{
From = "Pete Davidson",
Body = "Don't forget the kids have their soccer game this Friday. We have to supply end of game snacks.",
ShowButton = false
},
new Email
{
From = "OneDrive",
Body = "Your new album.\r\nYou uploaded some photos to your OneDrive and automatically created an album for you.",
ShowButton = false
},
new Email
{
From = "Twitter",
Body = "Here are some people we think you might like to follow:\r\n.#randomPerson\r\nAPersonYouMightKnow",
ShowButton = true
}
};
return MyEmails;
}
}
Would I need to use dependency properties in this case or should something else be used?
You have no need use dependency properties in this case, you could bind MoreBtn's Visibility to ShowButton property directly.
<Button Grid.Column="1"
x:Name="MoreBtn"
Background="Transparent"
Content=""
Visibility="{Binding ShowButton}"
FontFamily="Segoe MDL2 Assets"
HorizontalAlignment="Right"
VerticalAlignment="Top"
Margin="10"
Padding="10"
Click="MoreBtn_Click"/>
Starting in Windows 10, version 1607, the XAML framework provides a built in boolean to Visibility converter. The converter maps true to the Visible enumeration value and false to Collapsed so you can bind a Visibility property to a boolean without creating a converter. To use the built in converter, your app's minimum target SDK version must be 14393 or later. You can't use it when your app targets earlier versions of Windows 10. For more info about target versions, see Version adaptive code.
For previous version we could use BoolToVisibilityConverter to convert bool to visibility (install Microsoft.Toolkit.Uwp.UI nuget package).
Usage
<Page
x:Class="MasterDetailViewTest.MainPage"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:controls="using:Microsoft.Toolkit.Uwp.UI.Controls"
xmlns:converters="using:Microsoft.Toolkit.Uwp.UI.Converters"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:local="using:MasterDetailViewTest"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
Background="{ThemeResource ApplicationPageBackgroundThemeBrush}"
mc:Ignorable="d"
>
<Page.Resources>
<converters:BoolToVisibilityConverter x:Key="MyConveter" />
</Page.Resources>
......
<Button
x:Name="MoreBtn"
Grid.Column="1"
Margin="10"
Padding="10"
HorizontalAlignment="Right"
VerticalAlignment="Top"
Background="Transparent"
Click="MoreBtn_Click"
Content=""
FontFamily="Segoe MDL2 Assets"
Visibility="{Binding ShowButton, Converter={StaticResource MyConveter}}"
/>

How to change the Header image of TabItem through MouseOver?

I've a TabControl like this:
<TabControl>
<TabItem Header="playing" HorizontalAlignment="Left" Width="150" Tag="Tab1">
<TabItem.HeaderTemplate>
<DataTemplate>
<StackPanel Orientation="Horizontal">
<TextBlock Text="{Binding}" ToolTip="playing" />
<Image Margin="10,0,0,0" Source="/logo.png" Height="25"/>
</StackPanel>
</DataTemplate>
</TabItem.HeaderTemplate>
</TabItem>
...
In this TabControl I've three different TabItem, each tab item have a default image. My goal is to change the image TabItem where the user has positioned the mouse.
So in this case the TabItem 1 with ToolTip "playing" instead of logo.png should have logo2 when the mouse is over this tab item.
How can I do this?
Note: Please, note that I'm using mahapp, and I'm using a DataTemplate for keep the tooltip text without override the original style of mahapp tab item.
Try this:
XAML:
<Controls:MetroWindow
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:Controls="http://metro.mahapps.com/winfx/xaml/controls"
xmlns:local="clr-namespace:MahApps.Metro.Application21"
x:Class="MahApps.Metro.Application21.MainWindow"
BorderThickness="1"
BorderBrush="{DynamicResource AccentColorBrush}"
Icon="mahapps.metro.logo2.png"
Title="MainWindow"
Height="350"
Width="525">
<Controls:MetroWindow.Resources>
<DataTemplate x:Key="DataTemplate1">
<StackPanel x:Name="Panel1" Orientation="Horizontal">
<TextBlock Text="{Binding Text}" ToolTip="{Binding Text}" />
<Image x:Name="Image1" Source="{Binding Logo}" Margin="10,0,0,0" Height="25"/>
</StackPanel>
<DataTemplate.Triggers>
<Trigger SourceName="Panel1" Property="IsMouseOver" Value="true" >
<Setter TargetName="Image1" Property="Source" Value="logo4.png" />
</Trigger>
</DataTemplate.Triggers>
</DataTemplate>
</Controls:MetroWindow.Resources>
<Controls:MetroWindow.DataContext>
<local:MyViewModel/>
</Controls:MetroWindow.DataContext>
<Grid>
<TabControl ItemsSource="{Binding Data}" ItemTemplate="{StaticResource DataTemplate1}">
</TabControl>
</Grid>
ViewModel:
public class MyViewModel
{
public ObservableCollection<MyData> Data { get; set; }
public MyViewModel()
{
Data = new ObservableCollection<MyData>
{
new MyData {Logo = "logo1.png", Text = "playing 1" },
new MyData {Logo = "logo2.png", Text = "playing 2" },
new MyData {Logo = "logo3.png", Text = "playing 3" }
};
}
}

New to WPF - Updating TextBlock in Code behind causing NullReferenceException

I'm really new to WPF and I'm trying to update the text in a TextBlock whenever the selected item in a ListBox changes.
I added the ListBox and TextBlock to my XAML:
<Window x:Class="Blend_Test.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="MainWindow" WindowState="Maximized" ResizeMode="NoResize" Width="{DynamicResource {x:Static SystemParameters.PrimaryScreenWidthKey}}" Height="{DynamicResource {x:Static SystemParameters.PrimaryScreenHeightKey}}">
<Grid Background="#FFC10000">
<Grid.ColumnDefinitions>
<ColumnDefinition Width="*"/>
<ColumnDefinition Width="*"/>
</Grid.ColumnDefinitions>
<ListBox Grid.Column="0" Margin="20" FontSize="48" Name="VideoListBox" SelectedIndex="0" Cursor="None" SelectionChanged="VideoListBox_SelectionChanged">
<ListBoxItem Margin="20">Video 1</ListBoxItem>
<ListBoxItem Margin="20">Video 2</ListBoxItem>
<ListBoxItem Margin="20">Video 3</ListBoxItem>
<ListBoxItem Margin="20">Video 4</ListBoxItem>
</ListBox>
<TextBlock Grid.Column="1" Text="Lorem Ipsum" x:Name="VideoTextBlock" FontSize="48"></TextBlock>
</Grid>
</Window>
But now I'm not exactly sure what to add to my code behind. What I have so far is:
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
}
private void VideoListBox_SelectionChanged(object sender, System.Windows.Controls.SelectionChangedEventArgs e)
{
VideoTextBlock.Text = "Test";
}
}
However when I run this I'm getting a NullReferenceException error. I think I need to initialize the TextBlock somehow, but I'm not sure how to do this.
Try using a binding rather than an event handler:
<Window
x:Class="Blend_Test.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="MainWindow"
WindowState="Maximized"
ResizeMode="NoResize"
Width="{DynamicResource {x:Static SystemParameters.PrimaryScreenWidthKey}}"
Height="{DynamicResource {x:Static SystemParameters.PrimaryScreenHeightKey}}">
<Grid Background="#FFC10000">
<Grid.ColumnDefinitions>
<ColumnDefinition Width="*" />
<ColumnDefinition Width="*" />
</Grid.ColumnDefinitions>
<ListBox
Grid.Column="0"
Margin="20"
FontSize="48"
Name="VideoListBox"
SelectedIndex="0"
Cursor="None">
<ListBoxItem Margin="20">Video 1</ListBoxItem>
<ListBoxItem Margin="20">Video 2</ListBoxItem>
<ListBoxItem Margin="20">Video 3</ListBoxItem>
<ListBoxItem Margin="20">Video 4</ListBoxItem>
</ListBox>
<TextBlock
Grid.Column="1"
Text="{Binding SelectedItem.Content, ElementName=VideoListBox}"
x:Name="VideoTextBlock"
FontSize="48"/>
</Grid>
</Window>
If that doesn't work for your needs, I would just check for null before you try to access it:
private void VideoListBox_SelectionChanged(object sender, System.Windows.Controls.SelectionChangedEventArgs e)
{
if (VideoTextBlock != null)
{
VideoTextBlock.Text = "Test";
}
}

WPF Drag Drop, User Control becomes non-responsive

I'm doing some drag and drop between two ListBox items containing a UserControl, ClaimSectionTemplate as the DataTemplate for the items in the collection that are populating the source listbox.
Now I have 2 buttons on ClaimSectionTemplate, AddField and RemoveField, and they respectively add and remove fields from a child collection on the ClaimSection object that is shown in the ClaimSectionTemplate user control.
So what is happening is when I drop a ClaimSection into the target ListBox the original object becomes unresponsive no longer allowing me to interact with the user control.
MainWindow.Xaml
<ListBox Margin="13,12,12,12" Name="NewSections" Grid.Column="1" AllowDrop="True" Drop="NewSections_Drop">
<ListBox.ItemTemplate>
<DataTemplate>
<me:ClaimSectionTemplate />
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
</Grid>
</Window>
Main Window Drag Drop Handlers
private void ExistingSections_PreviewMouseLeftButtonDown(object sender, MouseButtonEventArgs e)
{
var parent = (ListBox)sender;
dragSource = parent;
var data = ExistingSections.SelectedItem;
if (data != null)
{
DragDrop.DoDragDrop(parent, data, DragDropEffects.Move);
}
}
private void NewSections_Drop(object sender, DragEventArgs e)
{
Models.ClaimSection dropData = (Models.ClaimSection)e.Data.GetData(typeof(Models.ClaimSection));
ClaimSectionsNew.addClaimSection(dropData);
ClaimSectionsExisting.removeClaimSection(dropData);
}
ClaimSectionTemplate.xaml
<UserControl x:Class="InsuranceBuildVer1.Views.ClaimSectionTemplate"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
mc:Ignorable="d"
d:DesignHeight="187" d:DesignWidth="300">
<Grid Height="185">
<TextBlock Height="23" Margin="12,12,12,0" Name="textBlock1" Text="{Binding Path=ClaimType}" VerticalAlignment="Top" />
<ListBox x:Name="FieldList" HorizontalAlignment="Left" Margin="10,71,0,12" Width="278" ItemsSource="{Binding Path=Fields.ClaimFields, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}">
<ListBox.ItemTemplate>
<DataTemplate>
<TextBox Text="{Binding Path=Identifier}" />
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
<Button Content="Add Field" Height="23" HorizontalAlignment="Left" Margin="12,42,0,0" Name="AddField" VerticalAlignment="Top" Width="75" Click="AddField_Click" />
<Button Content="Remove Field" Height="23" HorizontalAlignment="Left" Margin="103,42,0,0" Name="RemoveField" VerticalAlignment="Top" Width="96" Click="RemoveField_Click" />
</Grid>
</UserControl>

Categories

Resources