WPF controls not showing even make it visible - wpf

I encounter a problem that I am not sure how to fix. I have "AddAccount" (Button), "AccountsTextBlock" and a ListBox on the main window. If not user is added, the list box will be hidden, once user is added, it will show the ListBox, AddAccount and AccountsTextBlock on the same screen, but AddAccount and AccountsTextBlock will be at different positions from when there's no user. The problem is that AddAccount and AccountsTextBlock didn't show, but a dotted rectangle shows.
<Grid>
<Canvas>
<TextBlock x:Name="AddAccountTextBlock" HorizontalAlignment="Left" TextWrapping="Wrap" VerticalAlignment="Top" Height="60" Width="369" Text="Add account to allow for simple access to your company resources
" SnapsToDevicePixels="True" Canvas.Left="38" Canvas.Top="313"/>
<Button x:Name="AddAccount" Content="Add Account" Canvas.Left="145" Canvas.Top="333" HorizontalAlignment="Left" VerticalAlignment="Top" Width="140" RenderTransformOrigin="0.466,0.977" IsCancel="True" Height="40" Foreground="White" Background="Blue" Click="OnAddAccount"/>
<TextBlock x:Name="AccountsTextBlock" Canvas.Left="176" TextWrapping="Wrap" Text="Accounts" Canvas.Top="10" Height="33" Width="68" FontSize="16" FontFamily="Tahoma"/>
</Canvas>
<ListBox x:Name="accounts" HorizontalAlignment="Left" Height="237" VerticalAlignment="Top" Width="444" SelectionChanged="ListBox_SelectionChanged" Background="White" BorderBrush="White" Margin="0,47,0,0" RenderTransformOrigin="0.5,0.5">
<ListBox.RenderTransform>
<TransformGroup>
<ScaleTransform/>
<SkewTransform AngleX="0.384"/>
<RotateTransform/>
<TranslateTransform X="-0.794"/>
</TransformGroup>
</ListBox.RenderTransform>
<ListBox.ItemContainerStyle>
<Style TargetType="ListBoxItem">
<Setter Property="Height" Value="100"/>
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="ListBoxItem">
<Border Name="_Border" BorderBrush="Gray" BorderThickness="0.5"
Padding="2"
SnapsToDevicePixels="true">
<ContentPresenter />
</Border>
<ControlTemplate.Triggers>
<Trigger Property="IsSelected" Value="true">
<Setter TargetName="_Border" Property="Background" Value="LightSkyBlue"/>
</Trigger>
</ControlTemplate.Triggers>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
</ListBox.ItemContainerStyle>
<ListBox.ItemTemplate>
<DataTemplate>
<Grid Margin="3">
<Grid.ColumnDefinitions>
<ColumnDefinition Width="100"/>
<ColumnDefinition Width="*" />
</Grid.ColumnDefinitions>
<Image HorizontalAlignment="Left" VerticalAlignment="Center" Grid.Row="0" Grid.Column="0" Width="100" Source="{Binding Path=imagePath}" />
<TextBlock HorizontalAlignment="Center" VerticalAlignment="Center" Grid.Row="0" Grid.Column="1" Text="{Binding Path=userInfo}"></TextBlock>
</Grid>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
</Grid>
public MainWindow()
{
InitializeComponent();
using (RegistryKey key = Registry.CurrentUser.CreateSubKey(authenticatorRegistryKey))
{
Object valueStr = Registry.GetValue(authenticatorRegistryKey, addedUsersRegistryValueName, null);
if (valueStr == null)
{
//no users added yet, hide list box and move add button
accounts.Visibility = Visibility.Collapsed;
AccountsTextBlock.Visibility = Visibility.Collapsed;
Canvas.SetLeft(AddAccountTextBlock, (Application.Current.MainWindow.Width - AddAccountTextBlock.Width) / 2);
Canvas.SetTop(AddAccountTextBlock, (Application.Current.MainWindow.Height - AddAccountTextBlock.Height) / 2 - AddAccount.Height + 10);
Canvas.SetLeft(AddAccount, (Application.Current.MainWindow.Width - AddAccount.Width) / 2);
Canvas.SetTop(AddAccount, (Application.Current.MainWindow.Height - AddAccount.Height) / 2);
}
else
{
//show the added user
List<UserInfo> items = new List<UserInfo>();
items.Add(new UserInfo()
{
userInfo = "abcdefg",
imagePath = ""
});
accounts.ItemsSource = items;
AccountsTextBlock.Visibility = Visibility.Visible;
accounts.Visibility = Visibility.Visible;
}
}
}
private void OnAddAccount(object sender, RoutedEventArgs e)
{
SignInUrlWindow signInUrlWindow = new SignInUrlWindow();
signInUrlWindow.Left = Application.Current.MainWindow.Left;
signInUrlWindow.Top = Application.Current.MainWindow.Top;
signInUrlWindow.Width = Application.Current.MainWindow.Width;
signInUrlWindow.Height = Application.Current.MainWindow.Height;
signInUrlWindow.ShowDialog();
List<UserInfo> items = new List<UserInfo>();
items.Add(new UserInfo()
{
userInfo = "abcdefg",
imagePath = ""
});
accounts.ItemsSource = items;
accounts.Visibility = Visibility.Visible;
AddAccount.Visibility = Visibility.Visible;
AccountsTextBlock.Visibility = Visibility.Visible;
}

Related

ListView Popup key functionality

I have implemented a listview that appears as a popup list. Now I would like to add key functionalities to it, like if whenever up arrow is pressed in a text box it should select an item in my list view and if pressing of KEY_UP/DOWN is continued it should continue changing its index respectively.
This is the EditMessageTextBox and associated EditMessageTagPopup
This is the XAML code used:
<Grid x:Name="EditGrid"
Grid.Row="1"
Visibility="{Binding EditMessageControlVisibility}"
FocusManager.IsFocusScope="False"
VerticalAlignment="Center"
Grid.Column="1"
HorizontalAlignment="Stretch">
<Grid.RowDefinitions>
<RowDefinition Height="Auto" />
<RowDefinition Height="Auto" />
</Grid.RowDefinitions>
<Border x:Name="EditMessageBorder"
Grid.Row="0"
BorderThickness="1"
CornerRadius="1"
Margin="0,10,0,0"
BorderBrush="Gray">
<Grid>
<TextBlock FontSize="16"
Margin="10,0,0,3"
VerticalAlignment="Center"
HorizontalAlignment="Left"
Text="Edit message"
Foreground="{StaticResource brushWatermarkForeground}"
Visibility="{Binding ElementName=EditMessageTextBox, Path=Text.IsEmpty, Converter={StaticResource BooleanToVisibilityConverter}}" />
<TextBox Name="EditMessageTextBox"
Text="{Binding MessageToEdit, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}"
BorderBrush="Transparent"
BorderThickness="0"
Foreground="Black"
FontSize="16"
Margin="8,1,1,1"
VerticalContentAlignment="Center"
HorizontalContentAlignment="Left"
MinHeight="35"
ScrollViewer.VerticalScrollBarVisibility="Auto"
TextWrapping="Wrap"
AcceptsReturn="False"
KeyUp="OnEditMessage_KeyUp"
SpellCheck.IsEnabled="true" />
</Grid>
</Border>
<StackPanel Grid.Row="1"
Margin="0,10"
Orientation="Horizontal">
<Button Background="Transparent"
VerticalContentAlignment="Center"
Padding="5,2,5,3"
Foreground="Black"
BorderBrush="Gray"
BorderThickness="0.8"
Width="100"
materialDesign:ShadowAssist.ShadowDepth="Depth0"
Click="EditMessageCancelButton_Clicked">Cancel</Button>
<Button Name="EditMessageButton"
VerticalContentAlignment="Center"
Padding="5,2,5,3"
Background="#007a5a"
Foreground="White"
BorderBrush="#007a5a"
Margin="15,0,0,0"
materialDesign:ShadowAssist.ShadowDepth="Depth0"
BorderThickness="0.8"
IsEnabled="True"
Width="140"
Content="Save Changes"
Click="EditMessageSaveButton_Clicked" />
</StackPanel>
<Popup x:Name="EditMessageTagPopup"
AllowsTransparency="True"
IsOpen="{Binding IsOpenTagPopUp}"
StaysOpen="False"
Placement="Top"
PlacementTarget="{Binding ElementName=EditMessageTextBox}">
<Border materialDesign:ShadowAssist.ShadowDepth="Depth5"
CornerRadius="5"
Background="White"
BorderBrush="Black"
BorderThickness="0.8"
MaxHeight="200">
<ListView x:Name="EditTaggedUsers"
Focusable="True"
IsSynchronizedWithCurrentItem="True"
ItemsSource="{Binding Source={StaticResource UserListForTag}}"
SelectionChanged="EditMessageTagList_SelectionChanged">
<ListView.ItemContainerStyle>
<Style TargetType="ListViewItem">
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="ListViewItem">
<Border Name="_Border"
Padding="8">
<ContentPresenter />
</Border>
<ControlTemplate.Triggers>
<Trigger Property="IsMouseOver"
Value="True">
<Setter TargetName="_Border"
Property="Background"
Value="#FF3BD38E" />
<Setter Property="Foreground"
Value="White" />
</Trigger>
<Trigger Property="IsSelected"
Value="True">
<Setter TargetName="_Border"
Property="Background"
Value="#FF205B4B" />
<Setter Property="Foreground"
Value="White" />
</Trigger>
</ControlTemplate.Triggers>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
</ListView.ItemContainerStyle>
<ListView.ItemTemplate>
<DataTemplate>
<Grid Margin="-15,0,0,0"
Width="500">
<Grid.ColumnDefinitions>
<ColumnDefinition Width="70" />
<ColumnDefinition Width="*" />
</Grid.ColumnDefinitions>
<Rectangle Grid.Column="0"
RadiusY="5"
RadiusX="5"
Height="20"
Width="20">
<Rectangle.Fill>
<ImageBrush ImageSource="{Binding ProfileImage}"
Stretch="UniformToFill" />
</Rectangle.Fill>
</Rectangle>
<TextBlock Grid.Column="1"
Text="{Binding FullName}"
Margin="-10,0,0,0" />
</Grid>
</DataTemplate>
</ListView.ItemTemplate>
</ListView>
</Border>
</Popup>
</Grid>
and here is code behind:
ApplicationContext.StoredEditingMessage = (String)ApplicationContext.EditMessageText;
var messageData = ((TextBox)sender).DataContext as ChatsModel;
var EditMessagePopup = FindEditMessagePopup(MessageList);
Border EditEessageBorder = EditMessagePopup.Child as Border;
ListView EditMessageTagList = EditEessageBorder.Child as ListView;
Dispatcher?.Invoke(() =>
{
if (_contactsViewModel.GroupedChatByDate
.Find(x => messageData != null && x.MessageGuid == messageData.MessageGuid)
.IsOpenTagPopUp == false) return;
var index = _contactsViewModel.UsersListForTag.IndexOf(_contactsViewModel.UsersListForTag.FirstOrDefault(x => x.Selected == true));
switch (e.Key)
{
case Key.Up:
if (EditMessageTagList.SelectedIndex > 0)
{
EditMessageTagList.SelectedIndex -= 1;
EditMessageTagList.ScrollIntoView(EditMessageTagList.Items[EditMessageTagList.SelectedIndex]);
}
else
{
EditMessageTagList.SelectedIndex = _contactsViewModel.UsersListForTag.Count - 1;
EditMessageTagList.ScrollIntoView(EditMessageTagList.Items[EditMessageTagList.SelectedIndex]);
}
break;
case Key.Down:
if (EditMessageTagList.SelectedIndex + 1 == _contactsViewModel.UsersListForTag.Count)
{
EditMessageTagList.SelectedIndex = 0;
_contactsViewModel.UsersListForTag[index].Selected = true;
EditMessageTagList.ScrollIntoView(EditMessageTagList.Items[EditMessageTagList.SelectedIndex]);
}
else
{
EditMessageTagList.SelectedIndex += 1;
_contactsViewModel.UsersListForTag[index].Selected = true;
EditMessageTagList.ScrollIntoView(EditMessageTagList.Items[EditMessageTagList.SelectedIndex]);
}
break;
}
_contactsViewModel.UsersListForTag.ForEach(x => x.Selected = false);
if (index != -1)
{
_contactsViewModel.UsersListForTag[index].Selected = true;
}
});
I have tried adding an item in scroll into view() instead of selected index yet no update
when there is a perfect selection made this function is invoked from code behind
private void EditMessageTagList_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
try
{
var messageModel = ((ListView)sender).DataContext as ChatsModel;
if (((ListView)sender).SelectedItem is UserModel selectedUserForTag)
{
// _contactsViewModel.GroupedChatByDate.Find(x => messageModel != null && x.MessageGuid == messageModel.MessageGuid) .IsOpenTagPopUp = false;
string SelectedTag = (selectedUserForTag.Id == ApplicationContext.CurrentLoggedInUserGuid) ? $"{selectedUserForTag.UserName.Replace("(you) ", "")} " : $"{selectedUserForTag.UserName} ";
_contactsViewModel.GroupedChatByDate.Find
(x => messageModel != null && x.MessageGuid == messageModel.MessageGuid)
.MessageToEdit = "#" + SelectedTag;
}
// ((ListView) sender).SelectedItem = null;
}
catch (Exception exception)
{
LoggingManager.Error(exception);
}
}
Here is screen recording regarding issue
and
Here is working functionality
The problem is that after each navigation to the next item of the ListView you want to set focus to the selection TextBox which binds to the SelectedItem. Otherwise navigating the items of a ListView with the help of the arrow keys is already the default behavior of the ListView.
The simplest solution is to capture the keyboard input using UIElement.InputBinding on the selection TextBox (which enables to handle the keys in the view model) and then
Select the next/previous item
Scroll the SelectedItem into view
Move the focus to the selection TextBox
Move the caret of the selection TextBox to the end
DataItem.cs
class DataItem
{
public string FullName { get; set; }
public DataItem(string fullName) => this FullName = fullName;
}
ViewModel.cs
class ViewModel : INotifyPropertyChanged
{
public ObservableCollection<DataItem> DataItems { get; set; }
public ICommand SelectNextCommand => new AsyncRelayCommand(SelectNextItem);
public ICommand SelectPreviousCommand => new AsyncRelayCommand(SelectPreviousItem);
private bool IsSelectedItemChangeInternal { get; set; }
private DataItem selectedDataItem;
public DataItem SelectedDataItem
{
get => this.selectedDataItem;
set
{
this.selectedDataItem = value;
OnPropertyChanged();
// Do not filter the list when the selected item was set by the user
// e.g. by using arrow keys
if (!this.IsSelectedItemChangeInternal)
{
UpdateSearchFilter();
}
}
}
private string filterKey;
public string FilterKey
{
get => this.filterKey;
set
{
this.filterKey = value;
OnPropertyChanged();
// Only apply filters when the FilterKey was changed by the user
// e.g. by editing the edit TextBox that binds to this property
if (!this.IsSelectedItemChangeInternal)
{
ApplySearchFilter();
}
}
}
public ViewModel()
{
this.DataItems = new ObservableCollection<DataItems>();
for (var index = 0; index < 100; index++)
{
this.DataItems.Add(new DataItem("name " + index.ToString());
}
}
private void ApplySearchFilter()
{
ICollectionView collectionView = CollectionViewSource.GetDefaultView(this.Games);
this.IsSelectedItemChangeInternal = true;
collectionView.Filter = item =>
string.IsNullOrWhiteSpace(this.FilterKey) || (item as DetailItem).FullName.StartsWith(this.FilterKey);
// pre-select the first match
collectionView.MoveCurrentToFirst();
this.IsSelectedItemChangeInternal = false;
}
private void UpdateSearchFilter()
{
this.IsSelectedItemChangeInternal = true;
this.FilterKey = this.SelectedDataItem.FullName;
this.IsSelectedItemChangeInternal = false;
}
private void SelectNextItem()
{
ICollectionView collectionView = CollectionViewSource.GetDefaultView(this.DataItems);
collectionView.MoveCurrentToNext();
// Loop
if (collectionView.IsCurrentAfterLast)
{
collectionView.MoveCurrentToFirst();
}
}
private void SelectPreviousItem()
{
ICollectionView collectionView = CollectionViewSource.GetDefaultView(this.DataItems);
collectionView.MoveCurrentToPrevious();
// Loop
if (collectionView.IsCurrentBeforeFirst)
{
collectionView.MoveCurrentToLast();
}
}
public event PropertyChangedEventHandler PropertyChanged;
private void OnPropertyChanged([CallerMemberName] string propertyName = null)
{
this.PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName);
}
}
MainWindow.xaml.cs
private void AdjustFocus_OnSelectionChanged(object sender, SelectionChangedEventArgs e)
{
var listView = sender as ListView;
listView.ScrollIntoView(listView.SelectedItem);
Application.Current.Dispatcher.InvokeAsync(() =>
{
Keyboard.Focus(this.EditMessageTextBox);
this.EditMessageTextBox.CaretIndex = this.EditMessageTextBox.Text.Length;
});
}
private void AdjustFocus_OnOpened(object sender, EventArgs e)
{
this.EditTaggedUsers.Focus();
}
MainWindow.xaml
<Window>
<Window.DataContext>
<ViewModel />
</Window.DataContex>
<Grid>
<TextBox x:Name="EditMessageTextBox"
Text="{Binding FilterKey}">
<TextBox.InputBindings>
<KeyBinding Key="Down"
Command="{Binding SelectNextCommand}" />
<KeyBinding Key="Up"
Command="{Binding SelectPreviousCommand}" />
</TextBox.InputBindings>
</TextBox>
<Popup IsOpen="True"
Opened="AdjustFocus_OnOpened"
StaysOpen="False"
Placement="Top"
PlacementTarget="{Binding ElementName=EditMessageTextBox}">
<ListView IsSynchronizedWithCurrentItem="True"
Height="400"
SelectedItem="{Binding SelectedDataItem}"
ItemsSource="{Binding DataItems}"
SelectionChanged="AdjustFocus_OnSelectionChanged">
<ListView.ItemTemplate>
<DataTemplate DataType="{x:Type DataItem}">
<TextBox Text="{Binding FullName}" />
</DataTemplate>
</ListView.ItemTemplate>
</ListView>
</Popup>
</Grid>
</Window>
Remarks
As the navigation is done using the CollectionView of the ItemsSource the ListView.IsSynchronizedWithCurrentItem property must be set to true. Otherwise the navigation of the CollectionView won't effect the view.

How to bind custom dependency property in control template?

I have one class ChromeWindow which is derived from Window class. It has one custom dependency property
public class ChromeWindow : System.Windows.Window
{
public static readonly DependencyProperty TitleBarHeightProperty = DependencyProperty.Register("TitleBarHeight", typeof(int), typeof(ChromeWindow), new FrameworkPropertyMetadata(TitleBarHeightChangedCallback));
public int TitleBarHeight
{
get
{
return (int)GetValue(TitleBarHeightProperty);
}
set
{
SetValue(TitleBarHeightProperty, value);
}
}
private static void TitleBarHeightChangedCallback(DependencyObject d, DependencyPropertyChangedEventArgs e)
{
}
}
And ChromeWindow has its own control template as below.
<ControlTemplate x:Key="ChromeWindowTemplate" TargetType="local:ChromeWindow">
<Grid>
<AdornerDecorator>
<ContentPresenter />
</AdornerDecorator>
<StackPanel x:Name="PART_TitleBar"
HorizontalAlignment="Stretch"
VerticalAlignment="Top"
Background="Transparent"
Height="?">
<StackPanel HorizontalAlignment="Right"
VerticalAlignment="Top"
Orientation="Horizontal">
<Button x:Name="PART_MinimizeButton"
Width="34"
Height="26"
Style="{DynamicResource SystemButton}"
ToolTip="Minimize">
<Path Width="8"
Height="8"
HorizontalAlignment="Center"
VerticalAlignment="Center"
Data="F1M0,6L0,9 9,9 9,6 0,6z"
Fill="{Binding Foreground,
RelativeSource={RelativeSource Mode=FindAncestor,
AncestorType=Button}}" />
</Button>
<Button x:Name="PART_MaximizeButton"
Width="34"
Height="26"
Style="{DynamicResource SystemButton}"
ToolTip="Maximize">
<Path x:Name="PART_MaximizeButtonPath"
Width="10"
Height="10"
HorizontalAlignment="Center"
VerticalAlignment="Center"
Data="F1M0,0L0,9 9,9 9,0 0,0 0,3 8,3 8,8 1,8 1,3z"
Fill="{Binding Foreground,
RelativeSource={RelativeSource Mode=FindAncestor,
AncestorType=Button}}" />
</Button>
<Button x:Name="PART_CloseButton"
Width="34"
Height="26"
Style="{DynamicResource SystemButton}"
ToolTip="Close">
<Path Width="10"
Height="8"
HorizontalAlignment="Center"
VerticalAlignment="Center"
Data="F1M0,0L2,0 5,3 8,0 10,0 6,4 10,8 8,8 5,5 2,8 0,8 4,4 0,0z"
Fill="{Binding Foreground,
RelativeSource={RelativeSource Mode=FindAncestor,
AncestorType=Button}}" />
</Button>
</StackPanel>
</StackPanel>
<ResizeGrip x:Name="PART_ResizeGrip"
HorizontalAlignment="Right"
VerticalAlignment="Bottom"
Cursor="SizeNWSE"
Visibility="Hidden" />
</Grid>
</ControlTemplate>
How can I bind PART_Titlebar Height to custom dependency property called "TitleBarHeight" such that
If TitleBarHeight value is not specified, title bar height should
be calculated according to its child contents ?
If TitleBarHeight value is specified, use that value.
Thanks in advance.
The default value of the Height property is double.NaN, which indicates that there is no explicitly set height.
So you should change the type of your dependency property to double and set double.NaN as its default value:
public static readonly DependencyProperty TitleBarHeightProperty =
DependencyProperty.Register(
nameof(TitleBarHeight), typeof(double), typeof(ChromeWindow),
new FrameworkPropertyMetadata(double.NaN));
public double TitleBarHeight
{
get { return (double)GetValue(TitleBarHeightProperty); }
set { SetValue(TitleBarHeightProperty, value); }
}

Images aren't displayed in WPF ListBox

I'm trying to display images in a ListView. The images are being loaded through Entity Framework from a SQL Server database. Somehow the images don't get displayed in the ListView and I can't figure out why.
I've created a test Visual Studio project.
The images are stored in an ObservableCollection<ImageViewModel>:
private ObservableCollection<ImageViewModel> images;
public ObservableCollection<ImageViewModel> Images
{
get { return images; }
set { images = value; }
}
Please let me know if you need any further details. I'm grateful for any hints that I could try out.
I'll add a screenshot as soon as I have 10 reputation.
The ImageViewModel class looks like this:
using Common;
using TestImage.Model;
namespace TestImage.ViewModel
{
class ImageViewModel : ObservableObject
{
public ImageViewModel()
{
image = new ImageTable() { Name = "unknown"};
}
#region Properties
private ImageTable image;
public ImageTable Image
{
get { return image; }
set { image = value; }
}
public string Name
{
get { return image.Name; }
set
{
if (image.Name != value)
{
image.Name = value;
RaisePropertyChanged("Name");
}
}
}
public byte[] ImageBinary
{
get { return image.ImageBinary; }
set
{
if (image.ImageBinary != value)
{
image.ImageBinary = value;
RaisePropertyChanged("ImageBinary");
}
}
}
#endregion
}
}
The MainWindow.xaml looks like this:
<Window x:Class="TestImage.View.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="clr-namespace:TestImage.ViewModel"
Title="MainWindow" Height="375.6" Width="525">
<Window.DataContext>
<local:ImageLibrary/>
</Window.DataContext>
<Window.Resources>
<Style TargetType="{x:Type ListBox}">
<Setter Property="ItemTemplate">
<Setter.Value>
<DataTemplate>
<Border BorderBrush="Black" BorderThickness="4" CornerRadius="5" Margin="6">
<Image Source="{Binding Images}" Stretch="Fill" Width="100" Height="120" />
</Border>
</DataTemplate>
</Setter.Value>
</Setter>
<Setter Property="ItemsPanel">
<Setter.Value>
<ItemsPanelTemplate>
<WrapPanel />
</ItemsPanelTemplate>
</Setter.Value>
</Setter>
<Setter Property="ScrollViewer.HorizontalScrollBarVisibility" Value="Disabled"/>
</Style>
</Window.Resources>
<Grid Margin="0,0,0.4,1.4">
<ListBox Name="ListBoxImages" ItemsSource="{Binding Images}" Margin="413,40,20,31.6"/>
<Image Name="ImageSource" Source="{Binding SelectedImage}" HorizontalAlignment="Left" Height="148" Margin="14,90,0,0" VerticalAlignment="Top" Width="174"/>
<Button Name="ButtonPick" Content="Pick" HorizontalAlignment="Left" Margin="14,266,0,0" VerticalAlignment="Top" Width="75" RenderTransformOrigin="0.563,-0.731" Command="{Binding CommandPickImage}"/>
<Button Name="ButtonSave" Content="Save" HorizontalAlignment="Left" Margin="113,266,0,0" VerticalAlignment="Top" Width="75" RenderTransformOrigin="0.563,-0.731" Command="{Binding CommandSaveImage}" />
<Label Name="LabelFileName" Content="FileName" HorizontalAlignment="Left" Margin="14,40,0,0" VerticalAlignment="Top" Width="60"/>
<TextBox Name="TextBoxFileName" HorizontalAlignment="Left" Height="26" TextWrapping="Wrap" VerticalAlignment="Top" Width="314" Margin="79,40,0,0" Text="{Binding SelectedFileName}"/>
<Button Name="ButtonLoad" Content="Load" HorizontalAlignment="Left" Margin="113,293,0,0" VerticalAlignment="Top" Width="75" RenderTransformOrigin="0.563,-0.731" Command="{Binding CommandLoadImage}" />
<Image Source="{Binding SelectedImageDatabase}" HorizontalAlignment="Left" Height="148" Margin="193,90,0,0" VerticalAlignment="Top" Width="100"/>
</Grid>
</Window>
The binding in the ListBox ItemTemplate should be to the ImageViewModel's ImageBinary property, instead of Images:
<DataTemplate>
<Border ...>
<Image Source="{Binding ImageBinary}" .../>
</Border>
</DataTemplate>

EmptyTextValidationRule not behave as requested

Requirements: We have TextBox and when it is empty and loses focus, textbox will mark itself as "need to be filled" and raise popup.
Implementation: So far i became with following solution:
EmptyTextValidationRule actually check if textbox is empty and raise ValidationResult.
TextBox's style in XAML which responsible to to UI job (i.e. mark red color around textbox and raise popup.
Important NOTE: i cannot afford usage of code behind since this should be generic for ant textbox.
The problem is that my code is not working when textbox is empty and looses its focus.
<Window.Resources>
<Style TargetType="{x:Type TextBox}">
<Setter Property="Validation.ErrorTemplate">
<Setter.Value>
<ControlTemplate>
<DockPanel>
<Grid DockPanel.Dock="Right" Width="16" Height="16" VerticalAlignment="Center" Margin="3 0 0 0">
<Ellipse Width="16" Height="16" Fill="Red" />
<Ellipse Width="3" Height="8" VerticalAlignment="Top" HorizontalAlignment="Center" Margin="0 2 0 0" Fill="White" />
<Ellipse Width="2" Height="2" VerticalAlignment="Bottom" HorizontalAlignment="Center" Margin="0 0 0 2" Fill="White" />
</Grid>
<Border BorderBrush="Red" BorderThickness="2" CornerRadius="2">
<AdornedElementPlaceholder />
</Border>
</DockPanel>
</ControlTemplate>
</Setter.Value>
</Setter>
<Style.Triggers>
<Trigger Property="Validation.HasError" Value="true">
<Setter Property="ToolTip" Value="{Binding RelativeSource={x:Static RelativeSource.Self}, Path=(Validation.Errors)[0].ErrorContent}" />
</Trigger>
</Style.Triggers>
</Style>
</Window.Resources>
<Grid>
<TextBox Height="20" Width="100" />
<TextBox Grid.Row="0" Grid.Column="1" VerticalAlignment="Center" HorizontalAlignment="Left" MinWidth="150" MaxWidth="180" Margin="5,0">
<TextBox.Text>
<Binding Path="IncidentName" Mode="TwoWay" NotifyOnSourceUpdated="True" UpdateSourceTrigger="LostFocus">
<Binding.ValidationRules>
<validators:EmptyTextValidationRule />
</Binding.ValidationRules>
</Binding>
</TextBox.Text>
</TextBox>
</Grid>
EmptyTextValidationRule:
public class EmptyTextValidationRule : ValidationRule
{
private string m_errorText;
private const string TEXT_REQUERIED = "Text filed should not be empty";
public EmptyTextValidationRule()
{
}
public string ErrorText
{
get { return m_errorText; }
set
{
m_errorText = value;
}
}
public override ValidationResult Validate(object value, System.Globalization.CultureInfo cultureInfo)
{
string enterendText = value.ToString();
if (string.IsNullOrEmpty(enterendText))
{
if (string.IsNullOrEmpty(ErrorText))
return new ValidationResult(false, TEXT_REQUERIED);
else
return new ValidationResult(false, ErrorText);
}
return new ValidationResult(true, null);
}
}
This is not an attempt to answer your question, instead just pointing out a mistake in your code:
public override ValidationResult Validate(object value, System.Globalization.CultureInfo cultureInfo)
{
string enterendText = value.ToString(); //<< You'll get error here if value is null
if (string.IsNullOrEmpty(enterendText)) //<< No point checking here... too late!
{
if (string.IsNullOrEmpty(ErrorText))
return new ValidationResult(false, TEXT_REQUERIED);
else
return new ValidationResult(false, ErrorText);
}
return new ValidationResult(true, null);
}
Using this code, if value was ever null, then you'd get an error in the first if statement condition... you should do something like this instead:
string enterendText = string.Empty;
if (value == null || (enterendText = value.ToString()).Trim() == string.Empty)
{
...
}

Breadcrumb style with WPF-ListView

I want to create a simple breadcrumb bar with ListView. Following a simple wireframe screenshot what I would like to archive in the future:
Now, I already created already some code, mainly doing it with DataTemplates, which works actually quite well, but I have some visual problems I am not able to solve:
Main problem concerns the different width of the items. The center of an "arrow" should be stretched and the tail and head should be a fixed width...
The other problem is the visual style of the first and last items
Here's the actual code:
<ListView DockPanel.Dock="Left" ItemsSource="{Binding TagList}"
MinWidth="300" Background="Transparent" BorderThickness="0"
ScrollViewer.HorizontalScrollBarVisibility="Hidden"
ScrollViewer.VerticalScrollBarVisibility="Hidden" Margin="8,0,0,0">
<ListView.ItemsPanel>
<ItemsPanelTemplate>
<StackPanel Orientation="Horizontal"></StackPanel>
</ItemsPanelTemplate>
</ListView.ItemsPanel>
<ListView.ItemTemplate>
<DataTemplate>
<Grid Margin="-8,0,0,0">
<Grid>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="8"/>
<ColumnDefinition Width="Auto" />
<ColumnDefinition Width="8"/>
</Grid.ColumnDefinitions>
<Path Stretch="Fill" StrokeLineJoin="Round" Stroke="#FF000000" Fill="#FFC64242" Data="F1 M 112,144L 104,144L 112,160L 104,176L 112,176" HorizontalAlignment="Stretch" Height="Auto" VerticalAlignment="Stretch" Width="Auto"/>
<Grid HorizontalAlignment="Stretch" Height="Auto" VerticalAlignment="Stretch" Width="Auto" Grid.Column="1">
<Rectangle Stretch="Fill" Fill="#FFC64242" HorizontalAlignment="Stretch" Height="Auto" Margin="0.5" VerticalAlignment="Stretch" Width="Auto"/>
<Path Stretch="Fill" StrokeLineJoin="Round" Stroke="#FF000000" Data="F1 M 128,144L 160,144" HorizontalAlignment="Stretch" Height="1" Margin="0" VerticalAlignment="Top" Width="Auto"/>
<Path Stretch="Fill" StrokeLineJoin="Round" Stroke="#FF000000" Data="F1 M 128,176L 160,176" HorizontalAlignment="Stretch" Height="1" Margin="0" VerticalAlignment="Bottom" Width="Auto"/>
</Grid>
<Path Stretch="Fill" StrokeLineJoin="Round" Stroke="#FF000000" Fill="#FFC64242" Data="F1 M 168,144L 176,160L 168,176" Height="Auto" VerticalAlignment="Center" Width="8" HorizontalAlignment="Right" Grid.Column="2" d:LayoutOverrides="GridBox"/>
<DockPanel LastChildFill="True" Grid.ColumnSpan="2" Grid.Column="1">
<Label DockPanel.Dock="Left" FontSize="12" Content="{Binding Content, FallbackValue=Tagname n/a}" HorizontalAlignment="Left" Grid.Column="0" VerticalAlignment="Center" d:LayoutOverrides="Height" Margin="8,0"/>
<Button DockPanel.Dock="Right" Content="X" Background="Transparent" FontSize="12" Command="{Binding RemoveTagBtn}" Grid.Column="0" Width="13.077" d:LayoutOverrides="Height" VerticalAlignment="Center" Margin="0,0,8,0"/>
<!--<Border Background="#FFf7f7f7" BorderBrush="#FFc9c9c9" BorderThickness="1" CornerRadius="4" HorizontalAlignment="Left" Margin="0,0,0,5.96" d:LayoutOverrides="Height"/> -->
</DockPanel>
</Grid>
</Grid>
</DataTemplate>
</ListView.ItemTemplate>
</ListView>
Now as I had to find an answer myself in short time, this is my current solution. Also if you do not need the "selectable" feature of ListBox, you can exchange it with ItemControl.
Here's the code. Please be aware that I've commented out the "IsSelected" Triggers for the ItemStyleContainer...
<ListBox Padding="0" DockPanel.Dock="Left" ItemsSource="{Binding TagList}"
MinWidth="300" Background="Transparent" BorderThickness="0"
ScrollViewer.HorizontalScrollBarVisibility="Hidden"
ScrollViewer.VerticalScrollBarVisibility="Hidden">
<ListBox.ItemsPanel>
<ItemsPanelTemplate>
<StackPanel Margin="8,0,0,0" Orientation="Horizontal"></StackPanel>
</ItemsPanelTemplate>
</ListBox.ItemsPanel>
<ListBox.ItemContainerStyle>
<Style TargetType="{x:Type ListBoxItem}">
<Setter Property="Background" Value="{DynamicResource LXBarButtonBackgroundNormal}"/>
<Setter Property="BorderBrush" Value="{DynamicResource LXBarButtonBorderNormal}"/>
<Setter Property="HorizontalContentAlignment" Value="{Binding HorizontalContentAlignment, RelativeSource={RelativeSource AncestorType={x:Type ItemsControl}}}"/>
<Setter Property="VerticalContentAlignment" Value="{Binding VerticalContentAlignment, RelativeSource={RelativeSource AncestorType={x:Type ItemsControl}}}"/>
<Setter Property="Padding" Value="0"/>
<Setter Property="SnapsToDevicePixels" Value="true"/>
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="ListBoxItem">
<DockPanel LastChildFill="True" Margin="-8,0,0,0">
<Path DockPanel.Dock="Left" Stroke="{DynamicResource LXBarButtonBorderNormal}" Fill="{DynamicResource LXBarButtonBackgroundNormal}" Data="F1 M 112,144L 104,144L 112,160L 104,176L 112,176" Stretch="Fill" Height="32" Width="8" />
<Path DockPanel.Dock="Right" Stroke="{DynamicResource LXBarButtonBorderNormal}" Fill="{DynamicResource LXBarButtonBackgroundNormal}" Data="F1 M 168,144L 176,160L 168,176" Stretch="Fill" Height="32" Width="8" />
<Border Name="Border" SnapsToDevicePixels="{TemplateBinding SnapsToDevicePixels}" Background="{TemplateBinding Background}" BorderBrush="{TemplateBinding BorderBrush}" Padding="{TemplateBinding Padding}" BorderThickness="0,1" VerticalAlignment="Center">
<ContentPresenter />
<!--
<ControlTemplate.Triggers>
<Trigger Property="IsSelected" Value="true">
<Setter TargetName="Border" Property="Background"
Value="Blue"/>
</Trigger>
<Trigger Property="IsEnabled" Value="false">
<Setter Property="Foreground"
Value="Red"/>
</Trigger>
</ControlTemplate.Triggers>
-->
</Border>
</DockPanel>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
</ListBox.ItemContainerStyle>
<ListBox.ItemTemplate>
<DataTemplate>
<DockPanel VerticalAlignment="Center" Height="30">
<local:LXImageButton BorderThickness="0" Style="{DynamicResource LXBarImageButton}" Padding="0" DockPanel.Dock="Right" Background="Transparent" Command="{Binding RemoveTagBtn}" Height="16" Width="16"
NormalImage="/com.example.Views;component/Resources/Icons/Buttons/btnCloseXS_normal.png"
ActiveImage="/com.example.Views;component/Resources/Icons/Buttons/btnCloseXS_active.png"
HoverImage="/com.example.Views;component/Resources/Icons/Buttons/btnCloseXS_hover.png"
PressedImage="/com.example.Views;component/Resources/Icons/Buttons/btnCloseXS_hover.png"
DisabledImage="/com.example.Views;component/Resources/Icons/Buttons/btnCloseXS_passive.png"
/>
<Label DockPanel.Dock="Left" FontSize="12" Content="{Binding Content, FallbackValue=Tagname n/a}" VerticalAlignment="Center"/>
</DockPanel>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
I made a custom shape that renders the arrow that you want.
I used some code from the Rectangle class.
As for the part of styling the first and last elements. You will need some sort of AttachedBehavior that adjusts some property based on the item index.
using System;
using System.Windows.Shapes;
using System.Windows;
using System.Windows.Media;
namespace CustomShapes
{
public class SquaredArrow : Shape
{
protected Rect _rect = Rect.Empty;
#region TipOffset
/// <summary>
/// TipOffset Dependency Property
/// </summary>
public static readonly DependencyProperty TipOffsetProperty =
DependencyProperty.Register("TipOffset", typeof(double), typeof(SquaredArrow),
new FrameworkPropertyMetadata((double)10, FrameworkPropertyMetadataOptions.AffectsRender));
/// <summary>
/// Gets or sets the TipOffset property. This dependency property
/// indicates ....
/// </summary>
[System.ComponentModel.Category("SquaredArrow")]
public double TipOffset
{
get { return (double)GetValue(TipOffsetProperty); }
set { SetValue(TipOffsetProperty, value); }
}
#endregion
public SquaredArrow()
{
Rectangle r = new Rectangle();
r.Measure(new Size(100, 100));
r.Arrange(new Rect(0, 0, 100, 100));
}
static SquaredArrow()
{
StretchProperty.OverrideMetadata(typeof(SquaredArrow), new FrameworkPropertyMetadata(Stretch.Fill));
}
protected override Geometry DefiningGeometry
{
get { return CreateShape(); }
}
/// <summary>
/// Return the transformation applied to the geometry before rendering
/// </summary>
public override Transform GeometryTransform
{
get
{
return Transform.Identity;
}
}
/// <summary>
/// This is where the arrow shape is created.
/// </summary>
/// <returns></returns>
private Geometry CreateShape()
{
double width = _rect.Width;
double height = _rect.Height;
double borderOffset = GetStrokeThickness() / 2d;
PathGeometry g = new PathGeometry();
PathFigure figure = new PathFigure();
figure.IsClosed = true;
figure.StartPoint = new Point(borderOffset, borderOffset);
figure.Segments.Add(new LineSegment(new Point(width - TipOffset + borderOffset, borderOffset), true));
figure.Segments.Add(new LineSegment(new Point(width + borderOffset, height / 2d + borderOffset), true));
figure.Segments.Add(new LineSegment(new Point(width + borderOffset - TipOffset, height + borderOffset), true));
figure.Segments.Add(new LineSegment(new Point(borderOffset, height + borderOffset), true));
g.Figures.Add(figure);
return g;
}
/// <summary>
/// Updates DesiredSize of the Rectangle. Called by parent UIElement. This is the first pass of layout.
/// </summary>
/// <param name="constraint">Constraint size is an "upper limit" that Rectangle should not exceed.</param>
/// <returns>Rectangle's desired size.</returns>
protected override Size MeasureOverride(Size constraint)
{
if (Stretch == Stretch.UniformToFill)
{
double width = constraint.Width;
double height = constraint.Height;
if (Double.IsInfinity(width) && Double.IsInfinity(height))
{
return GetNaturalSize();
}
else if (Double.IsInfinity(width) || Double.IsInfinity(height))
{
width = Math.Min(width, height);
}
else
{
width = Math.Max(width, height);
}
return new Size(width, width);
}
return GetNaturalSize();
}
/// <summary>
/// Returns the final size of the shape and cachnes the bounds.
/// </summary>
protected override Size ArrangeOverride(Size finalSize)
{
// Since we do NOT want the RadiusX and RadiusY to change with the rendering transformation, we
// construct the rectangle to fit finalSize with the appropriate Stretch mode. The rendering
// transformation will thus be the identity.
double penThickness = GetStrokeThickness();
double margin = penThickness / 2;
_rect = new Rect(
margin, // X
margin, // Y
Math.Max(0, finalSize.Width - penThickness), // Width
Math.Max(0, finalSize.Height - penThickness)); // Height
switch (Stretch)
{
case Stretch.None:
// A 0 Rect.Width and Rect.Height rectangle
_rect.Width = _rect.Height = 0;
break;
case Stretch.Fill:
// The most common case: a rectangle that fills the box.
// _rect has already been initialized for that.
break;
case Stretch.Uniform:
// The maximal square that fits in the final box
if (_rect.Width > _rect.Height)
{
_rect.Width = _rect.Height;
}
else // _rect.Width <= _rect.Height
{
_rect.Height = _rect.Width;
}
break;
case Stretch.UniformToFill:
// The minimal square that fills the final box
if (_rect.Width < _rect.Height)
{
_rect.Width = _rect.Height;
}
else // _rect.Width >= _rect.Height
{
_rect.Height = _rect.Width;
}
break;
}
return finalSize;
}
/// <summary>
/// Get the natural size of the geometry that defines this shape
/// </summary>
protected Size GetNaturalSize()
{
double strokeThickness = GetStrokeThickness();
return new Size(strokeThickness, strokeThickness);
}
protected double GetStrokeThickness()
{
return this.StrokeThickness;
}
/// <summary>
/// Render callback.
/// </summary>
protected override void OnRender(DrawingContext drawingContext)
{
Pen pen = new Pen(Stroke, GetStrokeThickness());
drawingContext.DrawGeometry(Fill, pen, DefiningGeometry);
}
}
}

Resources