Good evening guys,
I'd really like to have a custom button with text and vector icon.. I searched for something similar but no luck..so I tried by myself to make a custom control but I am not able to make it works: no errors or warnings found but the icon doesn't appear at all.
Here below my code:
Custom control CS:
public class ThButton : Button
{
static ThButton()
{
DefaultStyleKeyProperty.OverrideMetadata(typeof(ThButton), new FrameworkPropertyMetadata(typeof(ThButton)));
}
public static readonly DependencyProperty IconProperty =
DependencyProperty.Register("Icon", typeof(Path), typeof(ThButton), new UIPropertyMetadata(null));
public Path Icon
{
get { return (Path)GetValue(IconProperty); }
set { SetValue(IconProperty, value); }
}
public static readonly DependencyProperty ThLabelProperty =
DependencyProperty.Register("ThLabel", typeof(string), typeof(ThButton), new UIPropertyMetadata(null));
public String ThLabel
{
get { return (String)GetValue(ThLabelProperty); }
set { SetValue(ThLabelProperty, value); }
}
}
generic.xaml (triggers etc. removed since not useful for this):
<ResourceDictionary
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="clr-namespace:CustomControlTest">
<Path x:Key="BoatIcon" Fill="Black" Data="M6,6H18V9.96L12,8L6,9.96M3.94,19H4C5.6,19 7,18.12 8,17C9,18.12 10.4,19 12,19C13.6,19 15,18.12 16,17C17,18.12 18.4,19 20,19H20.05L21.95,12.31C22.03,12.06 22,11.78 21.89,11.54C21.76,11.3 21.55,11.12 21.29,11.04L20,10.62V6C20,4.89 19.1,4 18,4H15V1H9V4H6A2,2 0 0,0 4,6V10.62L2.71,11.04C2.45,11.12 2.24,11.3 2.11,11.54C2,11.78 1.97,12.06 2.05,12.31M20,21C18.61,21 17.22,20.53 16,19.67C13.56,21.38 10.44,21.38 8,19.67C6.78,20.53 5.39,21 4,21H2V23H4C5.37,23 6.74,22.65 8,22C10.5,23.3 13.5,23.3 16,22C17.26,22.65 18.62,23 20,23H22V21H20Z" />
<Color x:Key="BackgroundColor1" A="255" R="0" G="133" B="209"/>
<Color x:Key="BackgroundColor2" A="255" R="0" G="61" B="94"/>
<Color x:Key="MouseOverBackgroundColor1" A="255" R="0" G="156" B="231"/>
<Color x:Key="MouseOverBackgroundColor2" A="255" R="0" G="90" B="155"/>
<Color x:Key="MousePressedBackgroundColor1" A="255" R="0" G="98" B="195"/>
<Color x:Key="MousePressedBackgroundColor2" A="255" R="0" G="36" B="72"/>
<Color x:Key="IsNotEnabledBackgroundColor1" A="255" R="233" G="233" B="233"/>
<Color x:Key="IsNotEnabledBackgroundColor2" A="255" R="240" G="240" B="240"/>
<SolidColorBrush x:Key="ThBorderBrush" Color="#ECECEC"></SolidColorBrush>
<Style TargetType="{x:Type local:ThButton}">
<Setter Property="BorderBrush" Value="{StaticResource ThBorderBrush}"/>
<Setter Property="BorderThickness" Value="2"/>
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="{x:Type local:ThButton}">
<Border x:Name="t"
Margin="{TemplateBinding Margin}"
BorderBrush="{TemplateBinding BorderBrush}"
BorderThickness="{TemplateBinding BorderThickness}"
CornerRadius="6">
<Border.Background>
<LinearGradientBrush StartPoint="0,0" EndPoint="0,1">
<LinearGradientBrush.GradientStops>
<GradientStop x:Name="BackgroundGradientStop1" Offset="0" Color="{StaticResource BackgroundColor1}"/>
<GradientStop x:Name="BackgroundGradientStop2" Offset="1" Color="{StaticResource BackgroundColor2}"/>
</LinearGradientBrush.GradientStops>
</LinearGradientBrush>
</Border.Background>
<StackPanel Orientation="Vertical" HorizontalAlignment="Center" VerticalAlignment="Center">
<Rectangle Width="20" Height="20" Fill="black" Margin="0,0,0,5">
<Rectangle.OpacityMask>
<VisualBrush Stretch="Fill" Visual="{TemplateBinding Icon}"/>
</Rectangle.OpacityMask>
</Rectangle>
<Label Content="{TemplateBinding ThLabel}"/>
</StackPanel>
</Border>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
</ResourceDictionary>
And finally mainWindow.xaml:
<local:ThButton Width="100" Icon="{StaticResource BoatIcon}" ThLabel="Test"/>
if I put the "{StaticResource BoatIcon}" in place of "{TemplateBinding Icon}" in Visual (generic.xaml) the icon appears so I suppose the problem is all about how I tried to use the DependencyProperty.
This can be done using a custom UserControl quite easily.
First, add your image to your project resources, and make 'Build Type = Resource' in the properties. Do this by selecting the newly added image and right clicking, then setting the above property.
Next, create a UserControl. Here's my XAML
<UserControl x:Class="ListViewDragAndDrop.UCPictureButton"
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"
xmlns:local="clr-namespace:ListViewDragAndDrop"
mc:Ignorable="d"
d:DesignHeight="32" d:DesignWidth="128">
<Grid>
<Button Click="Button_Click">
<StackPanel Orientation="Horizontal">
<Image Source="/Resources/solution.png"
Margin="4, 4, 8, 4"/>
<TextBlock Text="Button Text"
HorizontalAlignment="Center" VerticalAlignment="Center"/>
</StackPanel>
</Button>
</Grid>
</UserControl>
Make sure the 'Source' of the image is correct. What's shown above is where it's in my project which is the default.
Then the UserControl code behind:
public partial class UCPictureButton : UserControl
{
public event RoutedEventHandler RoutedButtonClick;
public UCPictureButton()
{
InitializeComponent();
}
private void Button_Click(object sender, RoutedEventArgs e)
{
RoutedButtonClick?.Invoke(this, e);
}
}
In the button click event, we invoke the RoutedEvent we declared there.
Now on your Main window or wherever you want to use the button:
<local:UCPictureButton Grid.Column="2" Width="120" Height="32">
<i:Interaction.Triggers>
<i:EventTrigger EventName="RoutedButtonClick">
<i:InvokeCommandAction Command="{Binding CmdButtonClick}"/>
</i:EventTrigger>
</i:Interaction.Triggers>
</local:UCPictureButton>
The i namespace is the interactivity namespace:
xmlns:i="http://schemas.microsoft.com/expression/2010/interactivity"
Now all you have to do is in your ViewModel simply hook up a method to the above declared CmdButtonClick command.
I'm using the MVVM Light toolkit and it looks like this:
public RelayCommand CmdButtonClick { get; private set; }
public MainViewModel(IDataService dataService)
{
CmdButtonClick = new RelayCommand(ButtonClick);
}
private void ButtonClick()
{
// Button action
}
Result:
Related
So I've been playing around with creating a custom title bar using WPF and this is what I have
<!--Add the WindowChrome object-->
<WindowChrome.WindowChrome>
<WindowChrome CaptionHeight="34" />
</WindowChrome.WindowChrome>
<Window.Resources>
<ResourceDictionary>
<Style x:Key="CaptionButtonStyle" TargetType="Button">
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="Button">
<Grid x:Name="LayoutRoot" Background="Transparent" Width="44" Height="30">
<TextBlock x:Name="txt" Text="{TemplateBinding Content}" FontFamily="Segoe MDL2 Assets" FontSize="10"
Foreground="Black" HorizontalAlignment="Center" VerticalAlignment="Center"
RenderOptions.ClearTypeHint="Auto" TextOptions.TextRenderingMode="Aliased" TextOptions.TextFormattingMode="Display"/>
</Grid>
<ControlTemplate.Triggers>
<Trigger Property="IsMouseOver" Value="True">
<Setter TargetName="LayoutRoot" Property="Background" Value="#E5E5E5"/>
<Setter TargetName="txt" Property="Foreground" Value="#000000"/>
</Trigger>
</ControlTemplate.Triggers>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
<!--Minimize-->
<Style x:Key="MinimizeButtonStyle" TargetType="Button" BasedOn="{StaticResource CaptionButtonStyle}">
<Setter Property="Content" Value=""/>
</Style>
<!--Maximize-->
<Style x:Key="MaximizeButtonStyle" TargetType="Button" BasedOn="{StaticResource CaptionButtonStyle}">
<Setter Property="Content" Value=""/>
</Style>
<!--Restore-->
<Style x:Key="RestoreButtonStyle" TargetType="Button" BasedOn="{StaticResource CaptionButtonStyle}">
<Setter Property="Content" Value=""/>
</Style>
<!--Close-->
<Style x:Key="CloseButtonStyle" TargetType="Button" BasedOn="{StaticResource CaptionButtonStyle}">
<Setter Property="Content" Value=""/>
</Style>
</ResourceDictionary>
</Window.Resources>
<!-- Title bar button commands -->
<Window.CommandBindings>
<CommandBinding Command="{x:Static SystemCommands.CloseWindowCommand}" CanExecute="CommandBinding_CanExecute" Executed="CommandBinding_Executed_Close" />
<CommandBinding Command="{x:Static SystemCommands.MaximizeWindowCommand}" CanExecute="CommandBinding_CanExecute" Executed="CommandBinding_Executed_Maximize" />
<CommandBinding Command="{x:Static SystemCommands.MinimizeWindowCommand}" CanExecute="CommandBinding_CanExecute" Executed="CommandBinding_Executed_Minimize" />
<CommandBinding Command="{x:Static SystemCommands.RestoreWindowCommand}" CanExecute="CommandBinding_CanExecute" Executed="CommandBinding_Executed_Restore" />
</Window.CommandBindings>
<Border x:Name="MainWindowBorder" BorderBrush="LightCoral" BorderThickness="0" >
<Grid x:Name="parentContainer" Background="LightBlue">
<Grid.RowDefinitions>
<RowDefinition Height ="Auto"/>
<RowDefinition Height ="*"/>
</Grid.RowDefinitions>
<!--Window chrome-->
<Grid Grid.Row="0" Height="30" Background="#F999">
<StackPanel Orientation="Horizontal" HorizontalAlignment="Left" VerticalAlignment="Center">
<!--App icon-->
<Image Source="/Resources/watermelon.ico" Width="18" Margin="2" HorizontalAlignment="Left" VerticalAlignment="Center" />
<TextBlock Text="Sweet App" FontFamily="Arial" Margin="4 3 0 0" />
</StackPanel>
<!--Caption buttons-->
<StackPanel Orientation="Horizontal" HorizontalAlignment="Right" >
<Button Style="{StaticResource MinimizeButtonStyle}" WindowChrome.IsHitTestVisibleInChrome="True" ToolTip="Minimize"
Command="{x:Static SystemCommands.MinimizeWindowCommand}"/>
<Button x:Name="RestoreButton" Visibility="Collapsed" Style="{StaticResource RestoreButtonStyle}"
Command="{x:Static SystemCommands.RestoreWindowCommand}" WindowChrome.IsHitTestVisibleInChrome="True" ToolTip="Restore"/>
<Button x:Name="MaximizeButton" Visibility="Visible" Style="{StaticResource MaximizeButtonStyle}"
Command="{x:Static SystemCommands.MaximizeWindowCommand}" WindowChrome.IsHitTestVisibleInChrome="True" ToolTip="Maximize" />
<Button Style="{StaticResource CloseButtonStyle}" WindowChrome.IsHitTestVisibleInChrome="True" ToolTip="Close"
Command="{x:Static SystemCommands.CloseWindowCommand}"/>
</StackPanel>
</Grid>
<!--App content-->
<Grid Grid.Row="1" x:Name="AppArea">
<Path Data="M50,0L100,50 50,100 0,50z" Fill="White" Stretch="Fill" Stroke="Black" StrokeThickness="2" />
</Grid>
</Grid>
</Border>
And that works great!
However if I were to comment out this part
<Window.CommandBindings>
<CommandBinding Command="{x:Static SystemCommands.CloseWindowCommand}" CanExecute="CommandBinding_CanExecute" Executed="CommandBinding_Executed_Close" />
<CommandBinding Command="{x:Static SystemCommands.MaximizeWindowCommand}" CanExecute="CommandBinding_CanExecute" Executed="CommandBinding_Executed_Maximize" />
<CommandBinding Command="{x:Static SystemCommands.MinimizeWindowCommand}" CanExecute="CommandBinding_CanExecute" Executed="CommandBinding_Executed_Minimize" />
<CommandBinding Command="{x:Static SystemCommands.RestoreWindowCommand}" CanExecute="CommandBinding_CanExecute" Executed="CommandBinding_Executed_Restore" />
</Window.CommandBindings>
Then when I hover over the buttons (Minimize, Maximize and Close) they don't change color anymore and there are no obvious errors presented to me. And as far as I know, it shouldn't change anything UI related since the actual trigger for changing the button background is already defined above in the Window.Resources
Why is this happening?
Here's the code behind
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
StateChanged += MainWindowStateChangeRaised;
}
// Can execute
private void CommandBinding_CanExecute(object sender, CanExecuteRoutedEventArgs e)
{
e.CanExecute = true;
}
// Minimize
private void CommandBinding_Executed_Minimize(object sender, ExecutedRoutedEventArgs e)
{
SystemCommands.MinimizeWindow(this);
}
// Maximize
private void CommandBinding_Executed_Maximize(object sender, ExecutedRoutedEventArgs e)
{
SystemCommands.MaximizeWindow(this);
}
// Restore
private void CommandBinding_Executed_Restore(object sender, ExecutedRoutedEventArgs e)
{
SystemCommands.RestoreWindow(this);
}
// Close
private void CommandBinding_Executed_Close(object sender, ExecutedRoutedEventArgs e)
{
SystemCommands.CloseWindow(this);
}
// State change
private void MainWindowStateChangeRaised(object sender, EventArgs e)
{
if (WindowState == WindowState.Maximized)
{
MainWindowBorder.BorderThickness = new Thickness(8);
RestoreButton.Visibility = Visibility.Visible;
MaximizeButton.Visibility = Visibility.Collapsed;
}
else
{
MainWindowBorder.BorderThickness = new Thickness(0);
RestoreButton.Visibility = Visibility.Collapsed;
MaximizeButton.Visibility = Visibility.Visible;
}
}
}
I am using Chart tool. Here is my wpf code:
<Window x:Class="UserGraphShow.GraphOutput"
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:DVC="clr-namespace:System.Windows.Controls.DataVisualization.Charting;assembly=System.Windows.Controls.DataVisualization.Toolkit"
mc:Ignorable="d"
Title="MainWindow" Height="446" Width="726" >
<Grid>
<DVC:Chart Name="Chart" Grid.ColumnSpan="3" Background="Blue" Title="Line">
<DVC:Chart.Series>
<DVC:LineSeries Title=" Your Graph" IndependentValueBinding="{Binding Path=Key}" DependentValueBinding="{Binding Path=Value}" Opacity="0" />
</DVC:Chart.Series>
<DVC:Chart.DataContext >
<Style TargetType="Grid" >
<Setter Property="Opacity" Value="0" />
</Style>
</DVC:Chart.DataContext>
<DVC:Chart.Axes>
<DVC:LinearAxis Orientation="Y" Minimum="-302" Maximum="0"/>
<DVC:LinearAxis Orientation="X" Maximum="509" Minimum="0"/>
<DVC:LinearAxis Visibility="Hidden"/>
</DVC:Chart.Axes>
</DVC:Chart>
<Button x:Name="Button" Content="Show" HorizontalAlignment="Left" Margin="8,10,0,0" VerticalAlignment="Top" Width="75" Grid.Column="1" Height="22" Click="button_Click"/>
</Grid>
</Window>
I am trying to display arrays of x[] and y[] as a plot.
Here is code of a button:
private void button_Click(object sender, RoutedEventArgs e)
{
var b = GetUserGraphUnfoInfo.FindXy("../../../Main_Logic/image.jpeg");
var x = b[0]; // array of x
var y = b[1]; // array of y
var ls = new LineSeries
{
IndependentValueBinding = new Binding("Key"),
DependentValueBinding = new Binding("Value")
};
var a = new KeyValuePair<int, int>[x.Length-1];
for (var i = 0; i < x.Length-1; i++)
a[i] = new KeyValuePair<int, int>(x[i], y[i]);
ls.ItemsSource = a;
Chart.Series.Clear();
Chart.Series.Add(ls);
}
Everything works ok, though the dots are too big, how do i remove them at all?
Here is what i get:
Create and apply a style to your data points, as below:
XAML:
<Window x:Class="WpfApplication342.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:dvc="clr-namespace:System.Windows.Controls.DataVisualization.Charting;assembly=System.Windows.Controls.DataVisualization.Toolkit"
xmlns:local="clr-namespace:WpfApplication342"
mc:Ignorable="d"
Title="MainWindow" Height="350" Width="525">
<Window.DataContext>
<PointCollection>1,10 2,20, 3,30</PointCollection>
</Window.DataContext>
<Window.Resources>
<Style x:Key="LineDataPointStyle1" TargetType="{x:Type dvc:LineDataPoint}">
<Setter Property="Background" Value="Orange"/>
<Setter Property="BorderBrush" Value="Gray"/>
<Setter Property="BorderThickness" Value="1"/>
<Setter Property="IsTabStop" Value="False"/>
<Setter Property="Width" Value="64"/>
<Setter Property="Height" Value="64"/>
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="{x:Type dvc:LineDataPoint}">
<Grid x:Name="Root" Opacity="1">
<Grid.ToolTip>
<ContentControl Content="{TemplateBinding FormattedDependentValue}"/>
</Grid.ToolTip>
<Ellipse Fill="{TemplateBinding Background}" Stroke="{TemplateBinding BorderBrush}"/>
<Ellipse RenderTransformOrigin="0.661,0.321">
<Ellipse.Fill>
<RadialGradientBrush GradientOrigin="0.681,0.308">
<GradientStop Color="Transparent"/>
<GradientStop Color="#FF3D3A3A" Offset="1"/>
</RadialGradientBrush>
</Ellipse.Fill>
</Ellipse>
<Ellipse x:Name="SelectionHighlight" Fill="Red" Opacity="0"/>
<Ellipse x:Name="MouseOverHighlight" Fill="White" Opacity="0"/>
</Grid>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
</Window.Resources>
<Grid>
<dvc:Chart>
<dvc:LineSeries ItemsSource="{Binding}"
DependentValuePath="Y"
IndependentValuePath="X"
DataPointStyle="{DynamicResource LineDataPointStyle1}"/>
</dvc:Chart>
</Grid>
Now you can manipulate the style in several ways to eliminate the dots: use transparent colors, set width and height to zero, or even modify the control template altogether. Setting width and height to zero:
I have a GanttControl with a TaskItemTemplate containing a Grid and a Rectangle which is responsible for the appearence of the tasks. The Rectangle has the properties Fill and Stroke. These properties are being set from StaticResources where the color of the tasks are defined. I try to bind the LinearGradientBrush to the property Color of my model.
There is my Xaml code:
<LinearGradientBrush x:Key="ParentBarFill" StartPoint="0,0" EndPoint="0,1">
<LinearGradientBrush.GradientStops>
<GradientStop Color="Black" Offset="0" />
<GradientStop Color="White" Offset="0.1" />
<GradientStop Color="Gray" Offset="0.2" />
<GradientStop Color="Black" Offset="0.6" />
</LinearGradientBrush.GradientStops>
</LinearGradientBrush>
** />
<SolidColorBrush x:Key="TaskItemBarStroke" Color="{Binding Color}"/> **<!--There is the Problem too-->**
<!-- Task look and feel styles -->
<!--Transparent-->
<Style TargetType="Thumb" x:Name="TransparentThumb" >
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="Thumb">
<Grid>
<Border CornerRadius="2" Background="Transparent" />
</Grid>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
<flexyGantt:FlexyGantt x:Name="fxgantt" Grid.Row="1" Grid.Column="0" ItemTemplate="{StaticResource TreeTemplate}"
TaskListBinding="{Binding EngineersInterval}" TaskStartTimeBinding="{Binding StartInteval, Mode=TwoWay}"
TaskEndTimeBinding="{Binding FinishInterval, Mode=TwoWay}" ParentTaskStartTimeBinding="{Binding OverallStartTime}"
ParentTaskEndTimeBinding="{Binding OverallEndTime}"
TreeHeaderContent="Teams" CustomSourceListViewTemplate="{StaticResource flexyGanttTableTemplate}"
OverlappedTasksRenderingOptimization="ShrinkHeight" RowHeight="25" TaskTimeChanged="Fxgantt_OnTaskTimeChanged"
>
<flexyGantt:FlexyGantt.TaskItemTemplate>
<DataTemplate>
<Grid ToolTipService.ToolTip="{Binding ToolTipText}">
<Rectangle x:Name="taskBar" HorizontalAlignment="Stretch"
Fill="{StaticResource TaskItemBarFill}" Stroke="{StaticResource TaskItemBarStroke}"
StrokeThickness="1" RadiusX="4" RadiusY="4"/>
<!--Include a thumb with name "dragThumb" to enable drag-moving the task functionality.
ZIndex=2 ensures this is drawn above the Rectangle-->
<Thumb x:Name="dragThumb" Canvas.ZIndex="2" Style="{StaticResource TransparentThumb}" />
<!--Include a thumb with name "resizeThumb" to enable resizing the task functionality
ZIndex=3 ensures this is drawn above the dragThumb-->
<Thumb x:Name="resizeThumb" Canvas.ZIndex="4" HorizontalAlignment="Right" Cursor="SizeWE"
Style="{StaticResource TransparentThumb}" Width="3" />
<!--Include a thumb with name "resizeStartThumb" to enable resizing to the left (changing starttime) functionality
ZIndex=3 ensures this is drawn above the dragThumb-->
<Thumb x:Name="resizeStartThumb" Canvas.ZIndex="3" HorizontalAlignment="Left" Cursor="SizeWE"
Style="{StaticResource TransparentThumb}" Width="3" Height="14"/>
</Grid>
</DataTemplate>
</flexyGantt:FlexyGantt.TaskItemTemplate>
</flexyGantt:FlexyGantt>
How can I bind this? Also me Model :
public class GanttIntervalModel : INotifyPropertyChanged
{
public Color Color
{
get { return _color; }
set
{
if (Equals(value, _color)) return;
_color = value;
OnPropertyChanged(nameof(Color));
}
}
[NotifyPropertyChangedInvocator]
protected virtual void OnPropertyChanged(string propertyName)
{
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
}
}
Problem
I have a Listbox control and when a user clicks a button they are able to add items to the control.
The issue I am having is that the Listbox control itself is not refreshing and displaying the new values that the user has added. I have debugged the code and the datasource is being updated with the new values.
Anyone have any ideas?
Code
The C#:
ObservableCollection<ITimeLineDataItem> listboxData = new ObservableCollection<ITimeLineDataItem>();
public ObservableCollection<ITimeLineDataItem> ListBoxData
{
get
{
return listboxData;
}
}
public Live()
{
InitializeComponent();
this.DataContext = this;
}
public void RefreshListbox()
{
ListSrc.ItemsSource = null;
//THE CODE GOES HERE WHERE I UPDATE THE DATASOURCE.
ListSrc.ItemsSource = ListBoxData;
}
XAML:
<Border BorderBrush="#d6786a" HorizontalAlignment="Stretch" VerticalAlignment="Stretch" BorderThickness="2" Grid.Column="15" Grid.Row="5" Grid.ColumnSpan="3">
<ListBox x:Name="ListSrc" Background="#ececec" ItemsSource="{Binding Path=ListBoxData}" dd:DragDrop.IsDragSource="True" VerticalAlignment="Stretch" HorizontalAlignment="Stretch" BorderBrush="Transparent" BorderThickness="0">
<ListBox.ItemContainerStyle>
<Style TargetType="ListBoxItem">
<Setter Property="Padding" Value="10" />
</Style>
</ListBox.ItemContainerStyle>
<ListBox.ItemsPanel>
<ItemsPanelTemplate>
<UniformGrid Columns="4" Margin="15"/>
</ItemsPanelTemplate>
</ListBox.ItemsPanel>
<ListBox.Resources>
<SolidColorBrush x:Key="{x:Static SystemColors.HighlightBrushKey}" Color="Transparent" />
<SolidColorBrush x:Key="{x:Static SystemColors.HighlightTextBrushKey}" Color="Black" />
<SolidColorBrush x:Key="{x:Static SystemColors.ControlBrushKey}" Color="Transparent" />
</ListBox.Resources>
</ListBox>
</Border>
You don't need to refresh. If the new item is added correctly to the source it should be visible on the list. However, can you update your post with the button click event code?
I have an observablecollection to create buttons the problem is that each of these buttons call the same event handler. i am trying to make it so that each button has their own unique id so that they can be distinguished from one another. the code used to create the button elements is
public class button
{
public bool IsEmpty { get; set; }
public int ID {get; set;}
public button(int button_Number)
{
IsEmpty = true;
ID = button_Number;
}
}
I is added to a observablecollection in the following code
ButtonCollection = new ObservableCollection<cChipVM>();
for ( int i = 0 ; i < iNumChips ; ++i )
{
ButtonCollection.Add( new button(i) );
}
the xml for the button is the following
<DataTemplate x:Key="ButtonTemplate">
<Button x:Name="Button" Uid="{Binding Path=ID}" Click="Button_Click" BorderBrush="Black" BorderThickness="1" Margin="7" Width="25" Height="25" ClickMode="Press" Opacity="0.9" Focusable="False" IsHitTestVisible="True" AllowDrop="True" IsTabStop="False">
<Button.Style>
<Style>
<Style.Triggers>
<DataTrigger Binding="{Binding Path=IsEmpty}" Value="false">
<Setter Property="Button.Background">
<Setter.Value>
<LinearGradientBrush EndPoint="0.5,1" StartPoint="0.5,0">
<GradientStop Color="#FF5ED426" Offset="0"/>
<GradientStop Color="White" Offset="1"/>
</LinearGradientBrush>
</Setter.Value>
</Setter>
</DataTrigger>
<DataTrigger Binding="{Binding Path=IsEmpty}" Value="true">
<Setter Property="Button.Background">
<Setter.Value>
<LinearGradientBrush EndPoint="0.5,1" StartPoint="0.5,0">
<GradientStop Color="#FF1766F0" Offset="0"/>
<GradientStop Color="White" Offset="1"/>
</LinearGradientBrush>
</Setter.Value>
</Setter>
</DataTrigger>
</Style.Triggers>
</Style>
</Button.Style>
</Button>
</DataTemplate>
When it tries to set the Uid with this method the system crashes, any recommendation how to fix this or any other solution where each button can have a unique ID
You can use Button.Tag property to store ID and in the handler inspect the value of Tag
<Button Tag="{Binding Path=ID}" Click="Button_Click" BorderBrush="Black" BorderThickness="1" Margin="7" Width="25" Height="25" ClickMode="Press" Opacity="0.9" Focusable="False" IsHitTestVisible="True" AllowDrop="True" IsTabStop="False">
UPDATE : Button click handler
public void Button_Click(object sender,EventArgs e)
{
var myButton = (Button)sender;
int id = Convert.ToInt32(myButton.Tag);
}