I feel like i'm really close to getting this to work. I have a calender, I want the user to be able to pick a month from a combobox and show the calender for that date. Right now nothing is being displayed no matter what I choose from the combobox. I can get it to work by using a listbox and a button event but its not really updating its just clearing and displaying the new month choosen. It's not the right way to do it. I've put a lot of time into this and if anybody can look at and maybe give me some pointers i'd really appreciate it.
--------Model Class---------
public partial class SchedulePage : Page, INotifyPropertyChanged
{
public int pick2;
public event PropertyChangedEventHandler PropertyChanged;
MainWindow _parentForm;
public int pick;
Schedule sched = new Schedule();
static GregorianCalendar _gc = new GregorianCalendar();
public SchedulePage(MainWindow parentForm)
{
InitializeComponent();
// this.PropertyChanged += comboMonth_SelectionChanged;
pick = Convert.ToInt32(comboMonth.SelectedItem);
_parentForm = parentForm;
}
public void NotifyPropertyChanged(String info)
{
if (PropertyChanged != null)
{
PropertyChanged(this, new PropertyChangedEventArgs(info));
}
}
private int _nameofmonth ;
public int NameofMonth
{
get
{
return this._nameofmonth;
}
set
{
if (value != this._nameofmonth)
{
this._nameofmonth = value;
NotifyPropertyChanged("NameofMonth");
}
}
}
// void TheViewModel_PropertyChanged(object src, PropertyChangedEventArgs e)
private void comboMonth_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
//{
// if (e.PropertyName == "NameofMonth")
// {
//var date = new DateTime(2011, 11, 1);
//makeCalender(date);
_parentForm.bindings.schedule.Clear();
var t = new List<Schedule>();
DateTime curr = DateTime.Now;
int jeez = comboMonth.SelectedIndex+1;
// comboMonth.Items.Add(curr.Month);
DateTime newcurr = new DateTime(2011, NameofMonth+1, 1);
// pickdate = datePickercal.SelectedDate;
// DateTime newcurr = new DateTime(curr.Year, curr.Month, 1);
var cal = System.Globalization.DateTimeFormatInfo.CurrentInfo.Calendar;
var ms = cal.GetWeekOfYear(new DateTime(newcurr.Year, newcurr.Month, 1), System.Globalization.CalendarWeekRule.FirstDay, System.DayOfWeek.Sunday);
for (var i = 1; newcurr.Month == NameofMonth+1; newcurr = newcurr.AddDays(1))
{
var month_week = (newcurr.Day / 7);
sched.MonthWeek = newcurr.GetWeekOfMonth().ToString();
sched.Month = newcurr.Month.ToString();
sched.Year = newcurr.Year.ToString();
sched.day = newcurr.Day.ToString();
sched.WeekOfYear = cal.GetWeekOfYear(newcurr, System.Globalization.CalendarWeekRule.FirstDay, DayOfWeek.Sunday).ToString();
sched.dayofweek = newcurr.DayOfWeek.ToString();
t.Add(sched);
_parentForm.bindings.schedule.Add(new Schedule { WeekNo = newcurr.GetWeekOfMonth() - 1, WeekDay = (int)newcurr.DayOfWeek, day = newcurr.Day.ToString() });
}
lblDate.Content = (newcurr.Month - 1) + "/" + newcurr.Year;
//testGrid.ItemsSource = t;
comboMonth.DataContext = _parentForm.bindings;
DataContext = _parentForm.bindings;
// }
}
----Part of the XAML------
<ComboBox SelectedIndex="{Binding NameofMonth}" Grid.ColumnSpan="2" Height="23" HorizontalAlignment="Left" Margin="6,0,0,0" Name="comboMonth" VerticalAlignment="Top" Width="120" SelectionChanged="comboMonth_SelectionChanged">
<ComboBoxItem Content="1" IsSelected="False" />
<ComboBoxItem Content="2" />
<ComboBoxItem Content="3" />
<ComboBoxItem Content="4" />
<ComboBoxItem Content="5" />
<ComboBoxItem Content="6" />
<ComboBoxItem Content="7" />
<ComboBoxItem Content="8" />
<ComboBoxItem Content="9" />
<ComboBoxItem Content="10" />
<ComboBoxItem Content="11" IsSelected="False" />
<ComboBoxItem Content="12" />
</ComboBox>
You need to make your poco class that is used within your ObservableCollection implement INotifyChanged.
Example:
<viewModels:LocationsViewModel x:Key="viewModel" />
.
.
.
<ListView
DataContext="{StaticResource viewModel}"
ItemsSource="{Binding Locations}"
IsItemClickEnabled="True"
ItemClick="GroupSection_ItemClick"
ContinuumNavigationTransitionInfo.ExitElementContainer="True">
<ListView.ItemTemplate>
<DataTemplate>
<StackPanel Orientation="Horizontal">
<TextBlock Text="{Binding Name}" Margin="0,0,10,0" Style="{ThemeResource ListViewItemTextBlockStyle}" />
<TextBlock Text="{Binding Latitude, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}" Style="{ThemeResource ListViewItemTextBlockStyle}" Margin="0,0,5,0"/>
<TextBlock Text="{Binding Longitude, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}" Style="{ThemeResource ListViewItemTextBlockStyle}" Margin="5,0,0,0" />
</StackPanel>
</DataTemplate>
</ListView.ItemTemplate>
</ListView>
public class LocationViewModel : BaseViewModel
{
ObservableCollection<Location> _locations = new ObservableCollection<Location>();
public ObservableCollection<Location> Locations
{
get
{
return _locations;
}
set
{
if (_locations != value)
{
_locations = value;
OnNotifyPropertyChanged();
}
}
}
}
public class Location : BaseViewModel
{
int _locationId = 0;
public int LocationId
{
get
{
return _locationId;
}
set
{
if (_locationId != value)
{
_locationId = value;
OnNotifyPropertyChanged();
}
}
}
string _name = null;
public string Name
{
get
{
return _name;
}
set
{
if (_name != value)
{
_name = value;
OnNotifyPropertyChanged();
}
}
}
float _latitude = 0;
public float Latitude
{
get
{
return _latitude;
}
set
{
if (_latitude != value)
{
_latitude = value;
OnNotifyPropertyChanged();
}
}
}
float _longitude = 0;
public float Longitude
{
get
{
return _longitude;
}
set
{
if (_longitude != value)
{
_longitude = value;
OnNotifyPropertyChanged();
}
}
}
}
public class BaseViewModel : INotifyPropertyChanged
{
#region Events
public event PropertyChangedEventHandler PropertyChanged;
#endregion
protected void OnNotifyPropertyChanged([CallerMemberName] string memberName = "")
{
if (PropertyChanged != null)
{
PropertyChanged(this, new PropertyChangedEventArgs(memberName));
}
}
}
Related
I have combo box with some contents. I want it to get reset to the first item when a button is clicked.
WPF and C#.net is used.
<ComboBox x:Name="categoriesComboBox" Height="40" Grid.Row="0" ItemsSource="{Binding Categories}" SelectedValue="{Binding SelectedCategory}"
VerticalContentAlignment="Center" Background="{StaticResource InventoryManagementAlternatingRowBackground}" BorderBrush="Transparent">
<ComboBox.ItemTemplate>
<DataTemplate>
<TextBlock Text="{Binding CategoryName}" FontSize="20" Margin="3,0" FontFamily="Malgun Gothic" />
</DataTemplate>
</ComboBox.ItemTemplate>
</ComboBox>
private void ClearFilter_Click(object sender, RoutedEventArgs e)
{
SearchFiltersControl s = new SearchFiltersControl();
s.ResetCategoryComboBox();
}
public void ResetCategoryComboBox()
{
categoriesComboBox.SelectedIndex = -1;
}
I am adding the ViewModel. Add I want to how to use this View Model to reset the ComboBox:
using System;
using System.Collections.ObjectModel;
namespace NextGen.Optik.UI.Presentation.ViewModels.Inventory.Contracts
{
public class SearchFilterCategoryViewModel : ViewModelBase
{
private int _categoryId;
public int CategoryId
{
get => _categoryId;
set
{
if (_categoryId != value)
{
_categoryId = value;
RaisePropertyChangedEvent();
}
}
}
private string _categoryName;
public string CategoryName
{
get => _categoryName;
set
{
if (_categoryName != value)
{
_categoryName = value;
RaisePropertyChangedEvent();
}
}
}
private ObservableCollection<SearchFilterViewModel> _filters = new ObservableCollection<SearchFilterViewModel>();
public ObservableCollection<SearchFilterViewModel> Filters
{
get => _filters;
set
{
if (_filters != value)
{
_filters = value;
RaisePropertyChangedEvent();
}
}
}
}
}
Expected Result: When the reset button is clicked, first item has to be selected.
Actual Results: Not getting reset.
I am current trying to build a form that displays different datagrids with different columns and data based on an input. I am selecting the appropriate DataTemplate and the columns show up correctly. I am binding the DataContext to the ContentControl. However, the data do not show up in the DataGrid.
Here's one of the templates in the app.xaml file.
<DataTemplate x:Key="templateHola1" DataType="{x:Type ContentControl}">
<DataGrid DataContext="{Binding}">
<DataGrid.Columns>
<DataGridTemplateColumn Header="Savings">
<DataGridTemplateColumn.CellTemplate>
<DataTemplate>
<Label Content="{Binding Savings}" />
</DataTemplate>
</DataGridTemplateColumn.CellTemplate>
</DataGridTemplateColumn>
<DataGridTemplateColumn Header="Total Income">
<DataGridTemplateColumn.CellTemplate>
<DataTemplate>
<Label Content="{Binding TotalIncome}" />
</DataTemplate>
</DataGridTemplateColumn.CellTemplate>
</DataGridTemplateColumn>
</DataGrid.Columns>
</DataGrid>
</DataTemplate>
Here's the form
<Window.Resources>
<local:HolaContentTemplateSelector x:Key="contentTemplateSelector" />
</Window.Resources>
<StackPanel Orientation="Vertical">
<ComboBox SelectionChanged="ComboBox_SelectionChanged_1" DropDownClosed="ComboBox_DropDownClosed_1">
<ComboBoxItem>Content 1</ComboBoxItem>
<ComboBoxItem>Content 2</ComboBoxItem>
<ComboBoxItem>Content 3</ComboBoxItem>
</ComboBox>
<ContentControl x:Name="ctrAbc" Content="{Binding}" ContentTemplateSelector="{StaticResource contentTemplateSelector}" />
<TextBox Text="{Binding Savings}" />
</StackPanel>
The last TextBox binding works, while the DataGrid bindings do not. Please illuminate me.
Edit
Savings and TotalIncome are properties in a class, whose list is used as the data source.
public class NetIncome : INotifyPropertyChanged
{
private int totalIncome = 5000;
private int rent = 2000;
private int food = 0;
private int misc = 0;
private int savings = 0;
public NetIncome()
{
savings = totalIncome - (rent + food + misc);
}
public int TotalIncome
{
get
{
return totalIncome;
}
set
{
if (TotalIncome != value)
{
totalIncome = value;
OnPropertyChanged("TotalIncome");
}
}
}
public int Rent
{
get
{
return rent;
}
set
{
if (Rent != value)
{
rent = value;
OnPropertyChanged("Rent");
UpdateSavings();
}
}
}
public int Food
{
get
{
return food;
}
set
{
if (Food != value)
{
food = value;
OnPropertyChanged("Food");
UpdateSavings();
}
}
}
public int Misc
{
get
{
return misc;
}
set
{
if (Misc != value)
{
misc = value;
OnPropertyChanged("Misc");
UpdateSavings();
}
}
}
public int Savings
{
get
{
return savings;
}
set
{
if (Savings != value)
{
savings = value;
OnPropertyChanged("Savings");
UpdateSavings();
}
}
}
private void UpdateSavings()
{
Savings = TotalIncome - (Rent + Misc + Food);
}
public event PropertyChangedEventHandler PropertyChanged;
private void OnPropertyChanged(String info)
{
PropertyChangedEventHandler handler = PropertyChanged;
if (handler != null)
{
handler(this, new PropertyChangedEventArgs(info));
}
}
}
I am very confuse in this topic.I am just taking One Single ListView.
<ListView.ItemTemplate >
<DataTemplate >
<Grid>
<Grid.RowDefinitions>
<RowDefinition Height="*"/>
<RowDefinition Height="*"/>
<RowDefinition Height="*"/>
</Grid.RowDefinitions>
<Image Source="Assets/button_register.png" Stretch="None" HorizontalAlignment="Left" VerticalAlignment="Top" Margin="8,15,8,8" />
<TextBlock Text="{Binding Sender}" FontSize="18" Foreground="Black" FontWeight="Bold" HorizontalAlignment="Center" Margin="0,12,0,0"/>
<Image Source="Assets/button_register.png" Grid.Row="1" Stretch="None" HorizontalAlignment="Right" VerticalAlignment="Top" Margin="4,0" />
<TextBlock Text="{Binding Receiver}" FontSize="18" Foreground="Black" FontWeight="Bold" HorizontalAlignment="Center" Grid.Row="1" Margin="0,12,0,0" VerticalAlignment="Top"/>
<Image Source="Assets/scroll_line_addcategory.png" Grid.Row="2" Stretch="None" HorizontalAlignment="Right" VerticalAlignment="Bottom" Margin="4,8,4,0" />
</Grid>
</DataTemplate>
</ListView.ItemTemplate>
</ListView>
And this list view bind with following class
public class User : INotifyPropertyChanged
{
public string Sender = string.Empty;
public string Receiver = string.Empty;
public string SenderVisibility = string.Empty;
public string ReceiverVisibility = string.Empty;
public event PropertyChangedEventHandler PropertyChanged;
public string send
{
get
{
return this.Sender;
}
set
{
if (value != this.Sender)
{
this.Sender = value;
NotifyPropertyChanged("send");
}
}
}
public string receive
{
get
{
return this.Receiver;
}
set
{
if (value != this.Receiver)
{
this.Receiver = value;
NotifyPropertyChanged("receive");
}
}
}
public string receivevisible
{
get
{
return this.ReceiverVisibility;
}
set
{
if (value != this.ReceiverVisibility)
{
this.ReceiverVisibility = value;
NotifyPropertyChanged("receivevisible");
}
}
}
public string sendervisibility
{
get
{
return this.SenderVisibility;
}
set
{
if (value != this.SenderVisibility)
{
this.SenderVisibility = value;
NotifyPropertyChanged("sendervisibility");
}
}
}
private void NotifyPropertyChanged([CallerMemberName] String propertyName = "")
{
if (PropertyChanged != null)
{
PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
}
}
}
While Application load at that time i'm simply load Static data at 6 time.
private void Page_Loaded(object sender, RoutedEventArgs e)
{
//List<User> ls = new List<User>();
for (int a = 0; a <= 5; a++)
{
User u = new User();
u.Sender = "Hello";
u.Receiver = "World";
ls.Add(u);
}
lst1.ItemsSource = ls;
Debug.WriteLine("Ls Count :: " + ls.Count);
}
but problem is occur while again i am Adding Data in this same list View After assigning source but Listview is not Update.
private void btnSend_Click(object sender, RoutedEventArgs e)
{
User n=new User(){
Sender="Chirag",
Receiver="Solanki"
};
ls.Add(n);
lst1.ItemsSource = ls;
}
So, Plz Help me if any one have any superb idea.
It's enough to set ItemsSource once. Setting it again won't change anything. Instead of List<User> you should use ObservableCollection<User>. It will handle changes in the list automatically.
Moreover, you have many errors in User class. Here's fixed code:
class User : INotifyPropertyChanged
{
private string sender = string.Empty;
private string receiver = string.Empty;
private string senderVisibility = string.Empty;
private string receiverVisibility = string.Empty;
public string Sender
{
get
{
return sender;
}
set
{
if (value != this.sender)
{
this.sender = value;
NotifyPropertyChanged("Sender");
}
}
}
public string Receiver
{
get
{
return this.receiver;
}
set
{
if (value != this.receiver)
{
this.receiver = value;
NotifyPropertyChanged("Receiver");
}
}
}
public string ReceiverVisibility
{
get
{
return this.receiverVisibility;
}
set
{
if (value != this.receiverVisibility)
{
this.receiverVisibility = value;
NotifyPropertyChanged("ReceiverVisibility");
}
}
}
public string SenderVisibility
{
get
{
return this.senderVisibility;
}
set
{
if (value != this.senderVisibility)
{
this.senderVisibility = value;
NotifyPropertyChanged("SenderVisibility");
}
}
}
private void NotifyPropertyChanged(string propertyName)
{
if (PropertyChanged != null)
{
PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
}
}
public event PropertyChangedEventHandler PropertyChanged;
}
When you call NotifyPropertyChanged(propertyName) the value of propertyName must match the name of the property. You messed up properties and fields. These private lowercase ones are fileds. Public camel case values are properties. In XAML you have to bind properties not fields.
Hello I am new to WPF and I am not sure how to do the data binding and the code behind to get my textbox and button to be enabled and disabled.
If you could show me how to get it to work in the example below it would help me out in my project.
XAML
<ComboBox Name="ComboBoxA"
Margin="5"
SelectedIndex="0" SelectionChanged="ComboBoxA_SelectionChanged" >
<ComboBox.ItemsPanel>
<ItemsPanelTemplate>
<WrapPanel Orientation="Vertical" Height="Auto" Margin="5" />
</ItemsPanelTemplate>
</ComboBox.ItemsPanel>
<ComboBoxItem Content="Option1" Width="72" />
<ComboBoxItem Content="Option2" Width="72" />
<ComboBoxItem Content="Option3" Width="72" />
</ComboBox>
<TextBox Name="TextBoxA"
Margin="5"
Width="200"
IsEnabled="{Binding TextBoxEnabled}" />
<Button Name="ButtonA"
Content="Next"
HorizontalAlignment="left"
Margin="5"
IsEnabled="{Binding ButtonEnabled} />
C#
private void ComboBoxA_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
TextBoxA = new TextBox();
ButtonA = new Button();
if (ComboBoxAfterProcessing.SelectedIndex == 0)
{
TextBoxA.IsEnabled = false;
ButtonA.IsEnabled = false;
}
else if (ComboBoxAfterProcessing.SelectedIndex == 1)
{
TextBoxA.IsEnabled = true;
ButtonA.IsEnabled = true;
}
else if (ComboBoxAfterProcessing.SelectedIndex == 2)
{
TextBoxA.IsEnabled = true;
ButtonA.IsEnabled = true;
}
}
Write a class as follows which shall look like below
public class ViewMole:INotifyPropertyChanged
{
public ViewMole()
{
ListValues = new List<string>() { "Option1", "Option2", "Option3", "Option4",
"Option5" };
}
public ICommand Click
{
get
{
return new RelayCommand();
}
}
public List<string> ListValues
{
get;
set;
}
string a;
public string A
{
get
{
return a;
}
set
{
a = value;
RaisePropertyChanged("A");
}
}
int index=0;
public int SelectedIndex
{
get
{
return index;
}
set
{
index = value;
RaisePropertyChanged("SelectedIndex");
A = ListValues[index];
if (index == 0)
{
IsEnabled = false;
}
else
{
IsEnabled = true;
}
}
}
bool isEnabled;
public bool IsEnabled
{
get
{
return isEnabled;
}
set
{
isEnabled = value;
RaisePropertyChanged("IsEnabled");
}
}
public event PropertyChangedEventHandler PropertyChanged;
private void RaisePropertyChanged(string propertyName)
{
if (PropertyChanged != null)
{
PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
}
}
}
Write another class which implements ICommand as below. This is to handel button click events
public class RelayCommand : ICommand
{
public bool CanExecute(object parameter)
{
return true;
}
public event EventHandler CanExecuteChanged;
public void Execute(object parameter)
{
MessageBox.Show("Button cliked");
}
}
Change your Xaml below
<ComboBox Name="ComboBoxA" SelectedIndex="{Binding SelectedIndex, UpdateSourceTrigger=PropertyChanged}" ItemsSource="{Binding ListValues}"/>
<TextBox Name="TextBoxA" Margin="5" Width="200" Text="{Binding A}" IsEnabled="{Binding IsEnabled}"/>
<Button Name="ButtonA" Content="Next" HorizontalAlignment="left" Margin="5" Command="{Binding Click}" IsEnabled="{Binding IsEnabled}"/>
In Xmal.cs set the data Context as beolw
public MainWindow()
{
InitializeComponent();
DataContext = new ViewMole();
}
Refer the below links to understand why INotifyPropertyChanged and ICommand has to be used
http://wpftutorial.net/INotifyPropertyChanged.html
http://msdn.microsoft.com/en-us/library/system.componentmodel.inotifypropertychanged.aspx
http://msdn.microsoft.com/en-us/library/system.windows.input.icommand.aspx
you can binding your textbox and button's IsEnabe Property to the Combox's SelectedIndex
Property and you neednot response to ComboBoxA_SelectionChanged Event. in order to let the
SelectedIndex change your button and textBox's IsEnabe you need a convetor in your binding
for example:
My WPF Application code generates panels on function call defined in .cs file. There is ItemControl used in code to generates these Panels . I want to move Panels Up or Down.
Example: There are three Panels PanelA, PanelB, PanelC now now there is button with each panel to move it up. Now i selected PanleB. i click on that button and PanelB will move up now they should be like PanelB, PanelA, PanelC
.XAML File:
<ItemsControl x:Name="lstItems" >
<ItemsControl.ItemTemplate>
<DataTemplate>
<StackPanel Orientation="Vertical">
<TextBox x:Name="txtText" Width="300" Height="100" Text="{Binding Text;, Mode=TwoWay}" FontSize="{Binding FontSize, Mode=OneWay}" />
<Slider Minimum="10" Maximum="30" Value="{Binding FontSize, Mode=TwoWay}" />
</StackPanel>
</DataTemplate>
</ItemsControl.ItemTemplate>
</ItemsControl>
.CS File:
public partial class MainWindow : Window
{
protected ObservableCollection<MyPanel> texts = new ObservableCollection<MyPanel>();
public MainWindow()
{
InitializeComponent();
texts.Add(new MyPanel() { Text = "Test 1" });
texts.Add(new MyPanel() { Text = "Test 2" });
lstItems.ItemsSource = texts;
}
}
public class MyPanel : INotifyPropertyChanged
{
private string _id;
private string _text;
private double _fontSize = 10;
public string Id
{
get { return _id; }
set
{
if (value != _id)
{
_id = value;
NotifyPropertyChanged();
}
}
}
public string Text
{
get { return _text; }
set
{
if (value != _text)
{
_text = value;
NotifyPropertyChanged();
}
}
}
public double FontSize
{
get { return _fontSize; }
set
{
if (value != _fontSize)
{
_fontSize = value;
NotifyPropertyChanged();
}
}
}
public event PropertyChangedEventHandler PropertyChanged;
protected void NotifyPropertyChanged(String propertyName = "")
{
if (PropertyChanged != null)
{
PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
}
}
}
EDIT:
XAML FILE:
<ItemsControl x:Name="lstItemsClassM" >
<ItemsControl.ItemTemplate>
<DataTemplate>
<StackPanel Orientation="Vertical">
<ComboBox x:Name="cboOccupation" IsEditable="False" HorizontalAlignment="Left"
Text="{Binding Path=Alignment, Mode=TwoWay}"
Margin="4" Width="140">
<ComboBoxItem>Right</ComboBoxItem>
<ComboBoxItem>Left</ComboBoxItem>
</ComboBox>
<Button Content="Move Up" Click="Button_Click_1" Tag="{Binding PKId}"/>
<Button Content="{Binding Alignment, Mode=TwoWay}" Click="Button_Click" Tag="{Binding PKId}" SourceUpdated="Button_SourceUpdated" />
<TextBox x:Name="txtText" Width="300" Height="100" Text="{Binding Text;, Mode=TwoWay}" FontSize="{Binding FontSize, Mode=OneWay}" TextAlignment="{Binding Alignment, Mode=OneWay}" />
<Slider Minimum="10" Maximum="30" Value="{Binding FontSize, Mode=TwoWay}" />
</StackPanel>
</DataTemplate>
</ItemsControl.ItemTemplate>
</ItemsControl>
.CS FILE:
public partial class Window2 : Window
{
protected ObservableCollection<ClassM> texts = new ObservableCollection<ClassM>();
int dv;
public Window2()
{
InitializeComponent();
dv=1;
texts.Add(new ClassM() { PKId=dv, Text = "Test 1" });
dv=2;
texts.Add(new ClassM() { PKId=dv, Text = "Test 2" });
lstItemsClassM.ItemsSource = texts;
}
private void Button_Click(object sender, RoutedEventArgs e)
{
var myValue = ((Button)sender).Tag;
foreach (var f in texts.ToList())
{
if (f.PKId.ToString() == myValue.ToString())
{
f._alignment = "Right";
MessageBox.Show(f._alignment);
}
}
}
private void Button_SourceUpdated(object sender, DataTransferEventArgs e)
{
var myValue = ((Button)sender).Tag;
foreach (var f in texts.ToList())
{
if (f.PKId.ToString() == myValue.ToString())
{
f._alignment = "Right";
MessageBox.Show(f._alignment);
}
}
}
private void Button_Click_1(object sender, RoutedEventArgs e)
{
var myValue = ((Button)sender).Tag;
foreach (var f in texts.ToList())
{
if (f.PKId.ToString() == myValue.ToString())
{
int s = f.PKId + 1;
texts.Move(f.PKId , s);
MessageBox.Show(f.PKId +" &&&&& " + s );
}
}
}
}
public class ClassM : INotifyPropertyChanged
{
private string _id;
private int _pkid;
private string _text;
private double _fontSize = 10;
public bool _isChecked { get; set; }
public string _alignment="Left";
public int PKId
{
get { return _pkid; }
set
{
if (value != _pkid)
{
_pkid = value;
NotifyPropertyChanged();
}
}
}
public string Id
{
get { return _id; }
set
{
if (value != _id)
{
_id = value;
NotifyPropertyChanged();
}
}
}
public bool IsChecked
{
get { return _isChecked; }
set
{
if (value != _isChecked)
{
_isChecked = value;
NotifyPropertyChanged();
}
}
}
public string Text
{
get { return _text; }
set
{
if (value != _text)
{
_text = value;
NotifyPropertyChanged();
}
}
}
public double FontSize
{
get { return _fontSize; }
set
{
if (value != _fontSize)
{
_fontSize = value;
NotifyPropertyChanged();
}
}
}
public string Alignment
{
get { return _alignment; }
set
{
if (value != _alignment)
{
_alignment = value;
NotifyPropertyChanged();
}
}
}
public event PropertyChangedEventHandler PropertyChanged;
protected void NotifyPropertyChanged(String propertyName = "")
{
if (PropertyChanged != null)
{
PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
}
}
}
}
Use the ObservableCollection's Move method:
private void Swap(MyPanel a, MyPanel b)
{
var indexA = texts.IndexOf(a);
var indexB = texts.IndexOf(b);
texts.Move(a,b);
}
Create the Command in your MainWindow, say MovePanelCommand and bind the Button commmand to this command and send the current item as the command parameter
<StackPanel Orientation="Vertical">
<TextBox x:Name="txtText" Width="300" Height="100" Text="{Binding Text;, Mode=TwoWay}" FontSize="{Binding FontSize, Mode=OneWay}" />
<Slider Minimum="10" Maximum="30" Value="{Binding FontSize, Mode=TwoWay}" />
<Button Command="{Binding DataContext.MovePanelCommand, RelativeSource={RelativeSource AncestorType={x:Type Window}}}" CommandParamter="{Binding}"/>
</StackPanel>
Now in command handler you will get your Panel you want to move up
private void MovePanelCommandHandler(object param)
{
MyPanel panel = param as MyPanel;
// Just move the panel one index up with validation if it is a first panel
}