C# WPF - Command Binding of toggle button not working - c#

Good day,
I would like to ask question on how to properly bind the RelayCommand UpdateUserCommand() in toggle button. Please see my code below
<UserControl x:Class="istock.View.UserMasterList"
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:materialDesign="http://materialdesigninxaml.net/winfx/xaml/themes"
xmlns:local="clr-namespace:istock.View"
mc:Ignorable="d"
MinHeight="450" Width="Auto" MinWidth="1024" FontFamily="Segoe UI LIght">
<Grid>
<Border Padding="30 15">
<StackPanel>
<Grid>
<TextBlock Text="User Management" FontSize="20" HorizontalAlignment="Left" Width="Auto" />
<StackPanel Orientation="Horizontal" HorizontalAlignment="Right" Width="Auto">
<Button x:Name="btnNew" Foreground="#FFFF">
<StackPanel Orientation="Horizontal">
<materialDesign:PackIcon Kind="PlusBoxOutline" Margin="0 5" />
<TextBlock Text="New User" Margin="5 3 5 0" />
</StackPanel>
</Button>
</StackPanel>
</Grid>
<ListView ItemsSource="{Binding Path = UserMasterListProp}">
<ListView.View>
<GridView>
<GridViewColumn Header="ID" Width="auto" DisplayMemberBinding="{Binding Path = Id}"></GridViewColumn>
<GridViewColumn Header="Username" Width="120" DisplayMemberBinding="{Binding Path = Username}"></GridViewColumn>
<GridViewColumn Header="Firstname" Width="120" DisplayMemberBinding="{Binding Path = Firstname}"></GridViewColumn>
<GridViewColumn Header="Middlename" Width="120" DisplayMemberBinding="{Binding Path = Middlename}"></GridViewColumn>
<GridViewColumn Header="Lastname" Width="120" DisplayMemberBinding="{Binding Path = Lastname}"></GridViewColumn>
<GridViewColumn Header="Role" Width="100" DisplayMemberBinding="{Binding Path = Role}"></GridViewColumn>
<GridViewColumn Header="Activated">
<GridViewColumn.CellTemplate>
<DataTemplate>
<ToggleButton x:Name="tbtnActivated" Style="{DynamicResource MaterialDesignSwitchToggleButton}" IsChecked="{Binding Path = Activated}" Command="{Binding Path = UserViewModel.UpdateUserCommand}" />
</DataTemplate>
</GridViewColumn.CellTemplate>
</GridViewColumn>
<GridViewColumn Header="Locked">
<GridViewColumn.CellTemplate>
<DataTemplate>
<ToggleButton x:Name="tbtnLocked" Style="{DynamicResource MaterialDesignSwitchToggleButton}" IsChecked="{Binding Path = Locked}" />
</DataTemplate>
</GridViewColumn.CellTemplate>
</GridViewColumn>
</GridView>
</ListView.View>
</ListView>
</StackPanel>
</Border>
</Grid>
Here is my Command Code which was initialized and CanExecute() method is always true.
public class RelayCommand : ICommand
{
private Action ExecuteCmd;
public RelayCommand(Action paramAction)
{
this.ExecuteCmd = paramAction;
}
public event EventHandler CanExecuteChanged;
public bool CanExecute(object parameter)
{
return true;
}
public void Execute(object parameter)
{
this.ExecuteCmd();
}
}
And Here's my code in ViewModel which the UpdateUser() method will be fired
by my UpdateUserCommand()
#region Update Command and Method
private RelayCommand updateUserCommand;
public RelayCommand UpdateUserCommand
{
get { return updateUserCommand; }
}
public void UpdateUser()
{
try
{
var isExist = this.userService.ApplyService_FindByIdOrUsername(UserModel.Id, UserModel.Username);
if(isExist == null)
{
var isUpdated = this.userService.ApplyService_Update(UserModel);
if (isUpdated == true)
{
this.Message = "Update sucesss.";
this.Populate_UserMasterList();
}
}
else
{
this.Message = "Update failed. ID or Username already exist.";
return;
}
}
catch(Exception ex)
{
MessageBox.Show(ex.Message.ToString());
return;
}
}
#endregion
Here is the implementation of the Data Context in Code Behind of the User Control
public partial class UserMasterList : UserControl
{
public UserMasterList()
{
InitializeComponent();
UserViewModel userViewModel = new UserViewModel();
this.DataContext = userViewModel;
}
}
Please help. If ever my code is confusing, I am open for question. Thanks

You could bind to a property of the parent UserControl using a {RelativeSource}:
<ToggleButton x:Name="tbtnActivated"
Style="{DynamicResource MaterialDesignSwitchToggleButton}"
IsChecked="{Binding Activated}"
Command="{Binding DataContext.UpdateUserCommand,
RelativeSource={RelativeSource AncestorType=UserControl}}" />

Related

Binding Listview SelectedItems for Actions

I'm struggling to bind 2 listviews selected items to my viewmodel.
The idea is to have a view with 2 listviews and 2 buttons in between to move the (multiple) selected items from 1 listview to another (2 way).
The view:
<Grid>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="*"/>
<ColumnDefinition Width="Auto"/>
<ColumnDefinition Width="*"/>
</Grid.ColumnDefinitions>
<ListView x:Name="DuamResources" Grid.Column="0" HorizontalAlignment="Stretch" VerticalAlignment="Stretch">
<ListView.View>
<GridView>
<GridViewColumn Header="Id" DisplayMemberBinding="{Binding Id}"/>
<GridViewColumn Header="Description" DisplayMemberBinding="{Binding Name}"/>
</GridView>
</ListView.View>
<ListView.GroupStyle>
<GroupStyle>
<GroupStyle.HeaderTemplate>
<DataTemplate>
<TextBlock FontWeight="Bold" FontSize="14" Text="{Binding Name}"/>
</DataTemplate>
</GroupStyle.HeaderTemplate>
</GroupStyle>
</ListView.GroupStyle>
</ListView>
<StackPanel Grid.Column="1" Orientation="Vertical" cal:Action.TargetWithoutContext="{Binding SelectedDuamResources}" VerticalAlignment="Center">
<Button Content="<" Width="40" Margin="5" cal:Message.Attach="AddSelectedResources($datacontext)"/>
<Button Content=">" Width="40" Margin="5"/>
</StackPanel>
<ListView x:Name="AvailableDuamResources" Grid.Column="2" HorizontalAlignment="Stretch" VerticalAlignment="Stretch">
<ListView.View>
<GridView>
<GridViewColumn Header="Id" DisplayMemberBinding="{Binding Id}"/>
<GridViewColumn Header="Description" DisplayMemberBinding="{Binding Name}"/>
</GridView>
</ListView.View>
<ListView.GroupStyle>
<GroupStyle HidesIfEmpty="True">
<GroupStyle.HeaderTemplate>
<DataTemplate>
<TextBlock FontWeight="Bold" FontSize="14" Text="{Binding Type}"/>
</DataTemplate>
</GroupStyle.HeaderTemplate>
</GroupStyle>
</ListView.GroupStyle>
</ListView>
</Grid>
The associated viewmodel properties:
private ObservableCollection<DuamResourceInfo> availableDuamResources;
public ObservableCollection<DuamResourceInfo> AvailableDuamResources
{
get { return availableDuamResources; }
set { availableDuamResources = value; NotifyOfPropertyChange(() => AvailableDuamResources); }
}
private ObservableCollection<DuamResourceInfo> selectedDuamResources;
public ObservableCollection<DuamResourceInfo> SelectedDuamResources
{
get { return selectedDuamResources; }
set { selectedDuamResources = value; NotifyOfPropertyChange(() => SelectedDuamResources); }
}
private ObservableCollection<DuamResourceInfo> duamResources;
public ObservableCollection<DuamResourceInfo> DuamResources
{
get { return duamResources; }
set { duamResources = value; NotifyOfPropertyChange(() => DuamResources); }
}
The code I want to achieve:
public void AddSelectedResources(IEnumerable<DuamResourceInfo> resources)
{
}
public void RemoveSelectedResources(IEnumerable<DuamResourceInfo> resources)
{
}
I'm using Caliburn Micro for MVVM. I know there are some conventions for binding but I'm not sure they apply to this scenario.
Any help is greatly appreciated!
Have you tried using "x:Bind" instead of "Binding"? For some reason in the past one or the other has worked for me, but not both, depending on the situation.

ListView bound to ObservableCollection<T> Doesn't update when Added to property

I am building a File Explorer an when the user DoubleClicks a TreeView it fires this event. Which fills an ObservableCollection<T> that is bound to my ListView called File_List.the FillCollection method does fill FileList with correct Information .
I have changed this from filling in c# to binding as I think that it will be easier to maintain. Thank you fro your time. There is this which tells me to impalement INotifyPropertyChanged I have that with RaisedPropertyChanged method.
private void folderItems_MouseDoubleClick(object sender, MouseButtonEventArgs e)
{
try
{
TreeViewItem item = (TreeViewItem)folderItems.SelectedItem;
FileAttributes attr = File.GetAttributes(item.Tag.ToString());
if ((attr & FileAttributes.Directory) == FileAttributes.Directory)
{
_ViewModel.FileList = FillFileModel.FillCollection(item.Tag.ToString());
}
else
{
//Do something else
}
}
catch (Exception) { }
}
FillFileModel Class
public static ObservableCollection<Files> FillCollection(string Path)
{
ObservableCollection<Files> files = new ObservableCollection<Files>();
var searchDirectory = new DirectoryInfo(Path);
try
{
Files getFile;
foreach (var file in searchDirectory.GetFiles())
{
getFile = new Files
{
FileName = file.Name,
FileSize = file.Length.ToString("#,##0 KB"),
DateModified = file.LastWriteTime,
FileType = getFileType(file.FullName)
};
files.Add(getFile);
}
}
catch (Exception)
{
}
return files;
}
the bound property:
public ObservableCollection<Files> FileList
{
get { return _FileList; }
set
{
if (_FileList!=value)
{
_FileList = value;
RaisedPropertyChanged("FileList");
}
}
}
RaisedPropertyChanged
public event PropertyChangedEventHandler PropertyChanged;
protected void RaisedPropertyChanged(string propertyName)
{
PropertyChangedEventHandler handler = this.PropertyChanged;
if (handler != null)
{
PropertyChangedEventArgs args = new PropertyChangedEventArgs(propertyName);
handler(this, args);
}
}
**XAML:**
<Window.Resources>
<uc:ucNav x:Key="Nav"/>
<uc:FileExplorerViewModel x:Key="viewModel"/>
<local:FileImageConverter x:Key="ImageConverter"/>
</Window.Resources>
<ListView Width="580" Margin="205,32,9,10" x:Name="File_List" ItemsSource="{Binding Path=FileList}">
<ListView.View>
<GridView>
<GridViewColumn Width="150" Header="Name" >
<GridViewColumn.CellTemplate>
<DataTemplate>
<StackPanel>
<Image Source="{Binding Converter={StaticResource ImageConverter}}" Height="20" Width="20" Stretch="Fill"/>
<TextBlock x:Name="file_Name" Text="{Binding FileName}"/>
</StackPanel>
</DataTemplate>
</GridViewColumn.CellTemplate>
</GridViewColumn>
<GridViewColumn Width="150">
<GridViewColumnHeader>
<TextBlock Text="Date Modified" />
</GridViewColumnHeader>
<GridViewColumn.CellTemplate>
<DataTemplate>
<TextBlock x:Name="Date_Modified" Text="{Binding DateModified}"/>
</DataTemplate>
</GridViewColumn.CellTemplate>
</GridViewColumn>
<GridViewColumn Width="150">
<GridViewColumnHeader>
<TextBlock Text="File Type" />
</GridViewColumnHeader>
<GridViewColumn.CellTemplate>
<DataTemplate>
<TextBlock x:Name="File_Type" Text="{Binding FileType}"/>
</DataTemplate>
</GridViewColumn.CellTemplate>
</GridViewColumn>
<GridViewColumn Width="130">
<GridViewColumnHeader>
<TextBlock Text="File Size" />
</GridViewColumnHeader>
<GridViewColumn.CellTemplate>
<DataTemplate>
<TextBlock x:Name="File_Size" Text="{Binding FileSize}"/>
</DataTemplate>
</GridViewColumn.CellTemplate>
</GridViewColumn>
</GridView>
</ListView.View>
</ListView>
It sounds like your DataContext is not set correctly, as the other code you have posted looks correct.
Place a breakpoint in your click handler and double-check that File_List.DataContext == _ViewModel
The DataContext is typically inherited from a parent control, or it can be set from the code-behind if this is the top-most window. In rare cases you can also bind or set the value, but this is typically not recommended as it can lead to confusion and debugging headaches.

C# How to check all checkboxes on listview

How to check all checkboxes on listview?
Listview xaml:
<ListView x:Name="List" HorizontalAlignment="Left" Height="559" Margin="10,10,0,0" VerticalAlignment="Top" Width="607" Grid.ColumnSpan="2" ScrollViewer.HorizontalScrollBarVisibility="Visible" ScrollViewer.VerticalScrollBarVisibility="Auto" IsMouseCapturedChanged="List_IsMouseCapturedChanged">
<ListView.ContextMenu>
<ContextMenu>
<MenuItem Name="Dodaj" Header="Dodaj" Click="DodajUtwor_Click"/>
<MenuItem Name="Usuń" Header="Usuń Zaznaczone" Click="UsuńUtwór_Click"/>
<MenuItem Name="Clear" Header="Wyczyść Listę" Click="ClearList_Click"/>
<MenuItem Name="Check" Header="Zaznacz Wszystkie" Click="SelectAll_Click"/>
</ContextMenu>
</ListView.ContextMenu>
<ListView.View>
<GridView>
<GridViewColumn Width="30" >
<GridViewColumn.CellTemplate>
<DataTemplate>
<StackPanel Orientation="Horizontal">
<CheckBox Name="CheckBox" Padding="10" IsChecked="{Binding IsChecked}"/>
<TextBlock Text="{Binding Data}"/>
</StackPanel>
</DataTemplate>
</GridViewColumn.CellTemplate>
</GridViewColumn>
<GridViewColumn Header="Nazwa Pliku" Width="100" DisplayMemberBinding="{Binding Nazwa}" />
<GridViewColumn Header="Tytuł" Width="100" DisplayMemberBinding="{Binding Tytuł}"/>
<GridViewColumn Header="Wykonawca" Width="100" DisplayMemberBinding="{Binding Autor}"/>
<GridViewColumn Header="Album" Width="100" DisplayMemberBinding="{Binding Album}"/>
<GridViewColumn Header="Nr" Width="100" DisplayMemberBinding="{Binding Nr}"/>
<GridViewColumn Header="Rok" Width="100" DisplayMemberBinding="{Binding Rok}"/>
<GridViewColumn Header="Gatunek" Width="100" DisplayMemberBinding="{Binding Gatunek}"/>
<GridViewColumn Header="Komantarze" Width="100" DisplayMemberBinding="{Binding Komentarze}"/>
<GridViewColumn Header="Okładka" Width="100" DisplayMemberBinding="{Binding Okładka}"/>
<GridViewColumn Header="Lokalizacja" Width="100" DisplayMemberBinding="{Binding Lokalizacja}"/>
</GridView>
</ListView.View>
</ListView>
Code:
private void Button_Click(object sender, RoutedEventArgs e)
{
MyItem selectedItem = (MyItem)this.List.SelectedItem;
selectedItem.IsChedked = true;
List.Items.Refresh();
}
Don't work.
I want to change all checkboxes on true in a listviev. I dont know how to use loop foreach. And how to delete items witch checkboxes on true?
I guess you might be looking for a checkbox in the header column and select all grid items when header checkbox got selected.
We can do this having simple child/sub viewmodels. Below code might help/solve your problem.
Xaml/View code -
<GridViewDataColumn DataMemberBinding="{Binding IsChecked}" >
<GridViewDataColumn.Header >
<CheckBox HorizontalAlignment="Left" IsChecked="{Binding RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type GridViewDataControl}}
,Path=DataContext.CheckAll}"
Command="{Binding RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type GridViewDataControl}}
,Path=DataContext.CheckAllCommand}"
CommandParameter="{Binding RelativeSource={RelativeSource Self}, Path=IsChecked}" />
</GridViewDataColumn.Header>
<GridViewDataColumn.CellTemplate>
<DataTemplate>
<StackPanel Orientation="Horizontal">
<CheckBox Name="CheckBox" Padding="10" IsChecked="{Binding IsChecked}" Command="{Binding RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type GridViewDataControl}}
,Path=DataContext.ItemCommand}" CommandParameter="{Binding}"/>
<TextBlock Text=y"{Binding Data}"/>
</StackPanel>
</DataTemplate>
</GridViewDataColumn.CellTemplate>
</GridViewDataColumn>
and you can have your view models as explained below.
class MainViewModel : Common.UserInterface.ViewModelBase, IDisposable
{
public MainViewModel()
{
CheckAllCommand = new DelegateCommand<bool>(OnCheckAllExecuted);
}
void OnCheckAllExecuted(bool status)
{
// Your logic goes here (if any)
CheckAll = items.All(item => item.IsChecked);
}
public DelegateCommand<ItemViewModel> ItemCommand { get; private set; }
private bool checkAll;
private ObservableCollection<ItemViewModel> items;
public DelegateCommand<bool> CheckAllCommand
{
get;
private set;
}
public ObservableCollection<ItemViewModel> Items
{
get
{
return items;
}
set
{
items = value;
OnPropertyChanged(() => Items);
}
}
public bool CheckAll
{
get { return checkAll; }
set
{
checkAll = value;
OnPropertyChanged(() => CheckAll);
}
}
}
class ItemViewModel : ViewModelBase
{
public bool ischecked;
public string data;
public new bool IsChecked
{
get { return isChecked; }
set
{
isChecked = value;
OnPropertyChanged("IsChecked");
}
}
public string Data
{
get { return data; }
set
{
data = value;
OnPropertyChanged("Data");
}
}
}

WPF-MVVM Radio Button generated automatically

I have an application where I present a Form. The form contains multiple Radio Buttons and they are displayed 1 next to each other. I need to load the colors from the list and create a radio button for each color, then when the users selects a color I want to grab the "SelectedItem" from the control. I know you can do that easily with a list but how do I do that when I need to place the controls next to each other ??
Code :
<Grid>
<StackPanel VerticalAlignment="Top">
<GroupBox Name="CheckBoxes" Margin="5" >
<StackPanel Name="wrpCheckBoxes" DataContext="{Binding ListParts}">
<RadioButton Name="chkRed" Content="{Binding Description}" Visibility="{Binding DataBindingModel.ColorRed}" Tag="{Binding ID}" />
<RadioButton Name="chkGreen" Content="Green" Visibility="{Binding DataBindingModel.ColorGreen}" />
<RadioButton Name="chkBlue" Content="Blue" Visibility="{Binding DataBindingModel.ColorBlue}" />
<RadioButton Name="chkGray" Content="Gray" Visibility="{Binding DataBindingModel.ColorGray}" />
<RadioButton Name="chkYellow" Content="Yellow" Visibility="{Binding DataBindingModel.ColorYellow}" />
<RadioButton Name="chkBlack" Content="Black" Visibility="{Binding DataBindingModel.ColorBlack}" />
</StackPanel>
</GroupBox>
</StackPanel>
<StackPanel VerticalAlignment="Bottom" Margin="5">
<ListView x:Name="listBoxItems" BorderThickness="1" ItemsSource="{Binding ListParts}">
<ListView.View>
<GridView>
<GridViewColumn Header="Index" DisplayMemberBinding="{Binding Index}" />
<GridViewColumn Header="Description" DisplayMemberBinding="{Binding Description}" />
<GridViewColumn Header="Price" DisplayMemberBinding="{Binding Price}" />
</GridView>
</ListView.View>
</ListView>
<!--<ListBox x:Name="listBoxItems" ItemsSource="{Binding ListParts}">
<ListBox.ItemTemplate>
<DataTemplate>
<RadioButton GroupName="rbList" Tag="{Binding}" Content="{Binding Description}" />
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>-->
</StackPanel>
</Grid>
Remark : the ListParts is just a list containing the colors, also this view is attached to a viewModel
ViewModel :
public class DataBindingViewModel : ViewModelBase
{
#region Private Fields
private DataBindingModel _DataBindingModel;
private List<PartsModel> _ListParts;
private string _Description1;
private int _TagID;
#endregion
#region Properties
public DataBindingModel DataBindingModel
{
get { return this._DataBindingModel; }
set
{
if (this._DataBindingModel == value)
return;
this._DataBindingModel = value;
OnPropertyChanged("DataBindingModel");
}
}
public List<PartsModel> ListParts
{
get { return this._ListParts; }
set
{
if (this._ListParts == value)
return;
this._ListParts = value;
OnPropertyChanged("ListParts");
}
}
public string Description1
{
get { return this._Description1; }
set
{
if (this._Description1 == value)
return;
this._Description1 = value;
OnPropertyChanged("Description1");
}
}
public int TagID
{
get { return this._TagID; }
set
{
if (this._TagID == value)
return;
this._TagID = value;
OnPropertyChanged("TagID");
}
}
#endregion
public DataBindingViewModel(DataBindingModel DataBinding)
{
this.DataBindingModel = DataBinding;
this.ListParts = Common.GetData();
}
}
And the Common Class is just laoding the Data :
public static class Common
{
public static List<PartsModel> GetData()
{
List<PartsModel> listParts = new List<PartsModel>();
listParts.Add(new PartsModel(1, "1234561", "Color Red", Convert.ToDecimal(15.99)));
listParts.Add(new PartsModel(2, "1234562", "Color Green", Convert.ToDecimal(17.00)));
listParts.Add(new PartsModel(3, "1234563", "Color Blue", Convert.ToDecimal(12.95)));
listParts.Add(new PartsModel(4, "1234564", "Color Gray", Convert.ToDecimal(9.95)));
listParts.Add(new PartsModel(5, "1234565", "Color Yellow", Convert.ToDecimal(10.55)));
listParts.Add(new PartsModel(6, "1234566", "Color Black", Convert.ToDecimal(99.99)));
return listParts;
}
}
How can I display the members of the ListParts on each of my radio button, without the use of a ListView ?
Let me know if you guys need more info and thanks for the answers
You can use ListBox.ItemsPanel to specify the type of panel you want - probably <StackPanel Orientation="Horizontal/>.
<ListBox>
<ListBox.ItemTemplate>
<DataTemplate>
<RadioButton GroupName="rbList" Tag="{Binding}" Content="{Binding Description}" />
</DataTemplate>
</ListBox.ItemTemplate>
<ListBox.ItemsPanel>
<ItemsPanelTemplate>
<StackPanel Orientation="Horizontal"
VerticalAlignment="Center"
HorizontalAlignment="Center"/>
</ItemsPanelTemplate>
<ListBox.ItemsPanel>
<ListBox>
See the examples in the ItemsPanel property documentation on MSDN for more information.

Add Background Color to Listview's Specific Row

Goal:
Change the listview's background color to light colored grey if the current time pass the appointment time. For instance, the time is 10.15 and you have background color for the 09.30 - 10.30 and 10.00 - 11.00.
Problem:
I do not know what syntax I need to use in order achieve the goal. I also reviews some advice from different website and their advice is not enough.
Information:
- I'am using Nhibernate to retrive the data.
- This is a usercontrol.
private void DisplayActivityBasedonSelectedDate()
{
DateTime aa = (DateTime) cdate_left.SelectedDate;
lvw_aktivitet.DataContext = _myNhibernateDataProvider.RetrieveAllActivitetBasedOnDate(aa);
DisplayDateInTheLabel();
}
public IList<Aktivitet_data> RetrieveAllActivitetBasedOnDate(DateTime pDatum)
{
return _session.GetNamedQuery("sp_retrieveAllActivitetBasedOnDate").SetDateTime("Datum", pDatum)
.SetResultTransformer(Transformers.AliasToBean(typeof(Aktivitet_data))).List<Aktivitet_data>();
}
public class Aktivitet_data
{
public string PK_Aktivitet_schema { get; set; }
public string Datum { get; set; }
public string Tid { get; set; }
public string Aktivitet { get; set; }
public string Total_platser { get; set; }
public string Bokade { get; set; }
public string Drop_in { get; set; }
}
XAML:
<UserControl x:Class="usercontrol_bokning.UserControl1"
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="300" d:DesignWidth="300">
<Grid Background="White" Margin="-127,0,-777,-316">
<ListView x:Name="lvw_aktivitet" HorizontalAlignment="Left" ItemsSource="{Binding}" SelectionMode="Single" Height="337" Margin="217,147,0,0" VerticalAlignment="Top" Width="365" SelectionChanged="lvw_aktivitet_SelectionChanged">
<ListView.View>
<GridView>
<GridViewColumn Header="Tid" Width="auto" DisplayMemberBinding="{Binding Path=Tid}" TextBlock.TextAlignment="Left" />
<GridViewColumn Header="Aktivitet" Width="auto" DisplayMemberBinding="{Binding Path=Aktivitet}" TextBlock.TextAlignment="Left" />
<GridViewColumn Header="Total platser" Width="auto" DisplayMemberBinding="{Binding Path=Total_platser}" TextBlock.TextAlignment="Center" />
<GridViewColumn Header="Bokade" Width="auto" DisplayMemberBinding="{Binding Path=Bokade}" TextBlock.TextAlignment="Center" />
<GridViewColumn Header="Drop in" Width="auto" >
<GridViewColumn.CellTemplate>
<DataTemplate>
<TextBlock TextAlignment="Right" Block.TextAlignment="Right" Text="{Binding Path=Drop_in}"/>
</DataTemplate>
</GridViewColumn.CellTemplate>
</GridViewColumn>
</GridView>
</ListView.View>
</ListView>
<Calendar x:Name="cdate_left" HorizontalAlignment="Left" Margin="10,147,0,0" VerticalAlignment="Top" SelectedDatesChanged="cdate_left_SelectedDatesChanged"/>
<Button x:Name="btn_idag" Content="Idag" HorizontalAlignment="Left" Margin="217,122,0,0" VerticalAlignment="Top" Width="75" Click="btn_idag_Click"/>
<Button x:Name="arrow__left" Click="Arrow_left_Click" Background="Transparent">
<Button.Template>
<ControlTemplate TargetType="{x:Type Button}">
<Image x:Name="bild_arrow_left" HorizontalAlignment="Left" Height="22" Margin="302,121,0,0" VerticalAlignment="Top" Width="22" Source="C:\Users\Administrator\Downloads\left.jpg" />
</ControlTemplate>
</Button.Template>
</Button>
<Button x:Name="arrow__right" Click="Arrow_right_Click" Background="Transparent" >
<Button.Template>
<ControlTemplate TargetType="{x:Type Button}">
<Image x:Name="bild_arrow_right" HorizontalAlignment="Left" Height="22" Margin="326,121,0,0" VerticalAlignment="Top" Width="22" Source="C:\Users\Administrator\Downloads\right.jpg"/>
</ControlTemplate>
</Button.Template>
</Button>
<Label x:Name="lbl_DisplayDateBySelection" Content="" HorizontalAlignment="Left" Margin="396,119,0,0" VerticalAlignment="Top"/>
<TabControl HorizontalAlignment="Left" Height="420" Margin="603,75,0,0" VerticalAlignment="Top" Width="589">
<TabItem Header="Bokade">
<Grid Background="#FFE5E5E5">
<ListView x:Name="lvw_bokade" HorizontalAlignment="Left" Height="335" Margin="10,46,0,0" VerticalAlignment="Top" Width="561">
<ListView.View>
<GridView>
<GridViewColumn/>
</GridView>
</ListView.View>
</ListView>
<Button Content="Ny plats" HorizontalAlignment="Left" Margin="10,21,0,0" VerticalAlignment="Top" Width="75"/>
</Grid>
</TabItem>
<TabItem Header="Avbokade">
<Grid Background="#FFE5E5E5" Margin="0,1,0,-1"/>
</TabItem>
<TabItem Header="Avregistrerade" HorizontalAlignment="Left" Height="20" VerticalAlignment="Top" Width="55">
<Grid Background="#FFE5E5E5"/>
</TabItem>
</TabControl>
<Label x:Name="lbl_instruktor" Content="Instruktör: " HorizontalAlignment="Left" Margin="1009,122,0,0" VerticalAlignment="Top"/>
</Grid>
</UserControl>
If you want it to update the items automatically you'll have to use some sort of a timer.
I used DispatcherTimer set globally in the UserControl
public DispatcherTimer dispatcher;
On Loaded / Ctor
dispatcher = new DispatcherTimer();
dispatcher.Tick += CheckTime;
dispatcher.Interval = new TimeSpan(0, 0, 5); //Change the interval to whatever suits you best
dispatcher.Start();
and the method to check your data:
private void CheckTime(object sender, EventArgs e)
{
ListBoxItem lbitem;
foreach (var item in lvw_aktivitet.Items)
{
if ((item as Aktivitet_data).Tid > DateTime.Now)
{
lbitem = (ListBoxItem)lvw_aktivitet.ItemContainerGenerator.ContainerFromItem(item);
lbitem.Background = new SolidColorBrush(Colors.Gray);
}
}
}

Categories