Access Custom Class Variables in a ViewModel through binding - c#

What I want to do is to be able to access an object's properties through a bound textblock that is found in a viewModel class. So say I want to access the OrderID of the Orders class in a bound textblock that is stored in a viewModel class.
What I have for that is:
<textblock text="{Binding Path=Order.OrderID}"/>
This is connected to the order's orderID as when I change the OrderID in the ViewModel class the change is reflected in the textblock. The problem occurs when I try to load the OrderID from another class.
The Other class:
public class ModifyOrder
{
private ViewModel boundData;
public ModifyOrder()
{
boundData = new ViewModel();
}
public void ChangeOrderID()
{
boundData.Order.OrderID = 10;
}
}
The changes here don't get transfered to the static _Order in the ViewModel class.
This is the viewModel class:
public class ViewModel : INotifyPropertyChanged
{
private Orders _Order;
public Orders Order
{
get { return _Order; }
set
{
if (_Order != value)
{
_Order = value;
}
}
}
public ViewModel()
{
Order = new Orders();
}
public event PropertyChangedEventHandler PropertyChanged;
private void OnPropertyChanged([CallerMemberName] string propertyName = null)
{
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
}
}
I have the ViewModel class loaded into the UI's DataContext and my other bound variables in the ViewModel class work fine but for some reason either the bound textblock isn't accessing the Order.OrderID (Which I don't think is the problem since I can modify the Order.OrderID in the ViewModel class and the changes are reflected) OR the class that's modifying my Order isn't able to modify the OrderID.
I've already tried to load a new Order class with the new OrderID and then try to load the ViewModel's _Order with the ModifyOrder's new Order but that hasn't worked out either.
This is the Orders class:
public class Orders : INotifyPropertyChanged
{
private int _OrderID;
public int OrderID
{
get { return _OrderID; }
set
{
if(_OrderID != value)
{
_OrderID = Value
OnPropertyChanged(nameof(OrderID));
}
}
}
public event PropertyChangedEventHandler PropertyChanged;
private void OnPropertyChanged([CallerMemberName] string propertyName = null)
{
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
}
}
<Page x:Class="SPWally.FunctionalPages.LookupOrders"
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:SPWally.FunctionalPages"
mc:Ignorable="d"
d:DesignHeight="450" d:DesignWidth="800"
Title="LookupOrders">
<Grid Background="AliceBlue">
<Grid.RowDefinitions>
<RowDefinition Height="50"/>
<RowDefinition Height="30"/>
<RowDefinition Height="*"/>
<RowDefinition Height="20"/>
<RowDefinition Height="20"/>
<RowDefinition Height="20"/>
<RowDefinition Height="20"/>
<RowDefinition Height="20"/>
<RowDefinition Height="20"/>
<RowDefinition Height="*"/>
<RowDefinition Height="50"/>
</Grid.RowDefinitions>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="*"/>
<ColumnDefinition Width="*"/>
</Grid.ColumnDefinitions>
<TextBlock Grid.Row="0" Grid.Column="0" Grid.ColumnSpan="2" HorizontalAlignment="Center" VerticalAlignment="Center" FontSize="30" Text="Search For Order" />
<TextBlock Grid.Row="1" Grid.Column="0" HorizontalAlignment="Right" VerticalAlignment="Center" Margin="0,0,335,0" Text="OrderID: " />
<TextBox Grid.Row="1" Grid.Column="0" HorizontalAlignment="Right" VerticalAlignment="Center" Width="300" Margin="0,0,20,0" Text="{Binding Path=OrderIDSearch, Mode=OneWayToSource, UpdateSourceTrigger=PropertyChanged}" />
<Button Grid.Row="1" Grid.Column="1" HorizontalAlignment="Left" VerticalAlignment="Center" Width="40" Height="20" Margin="10,0,0,0" Content="Find" Click="Find_Click" />
<Button Grid.Row="1" Grid.Column="1" HorizontalAlignment="Left" VerticalAlignment="Center" Width="50" Height="20" Margin="70,0,0,0" Content="Refund" Click="Refund_Click" />
<TextBlock Grid.Row="3" Grid.Column="0" HorizontalAlignment="Right" VerticalAlignment="Center" Margin="0,0,100,0" Text="OrderID:"/>
<TextBlock Grid.Row="4" Grid.Column="0" HorizontalAlignment="Right" VerticalAlignment="Center" Margin="0,0,100,0" Text="Customer:"/>
<TextBlock Grid.Row="5" Grid.Column="0" HorizontalAlignment="Right" VerticalAlignment="Center" Margin="0,0,100,0" Text="Product:"/>
<TextBlock Grid.Row="6" Grid.Column="0" HorizontalAlignment="Right" VerticalAlignment="Center" Margin="0,0,100,0" Text="Branch:"/>
<TextBlock Grid.Row="7" Grid.Column="0" HorizontalAlignment="Right" VerticalAlignment="Center" Margin="0,0,100,0" Text="Sales Price:"/>
<TextBlock Grid.Row="8" Grid.Column="0" HorizontalAlignment="Right" VerticalAlignment="Center" Margin="0,0,100,0" Text="Quantity:"/>
<TextBlock Grid.Row="3" Grid.Column="0" Grid.ColumnSpan="2" HorizontalAlignment="Center" VerticalAlignment="Center" Width="200" Margin="30,0,0,0" Text="{Binding Path=Order.OrderID, Mode=TwoWay}"/>
<TextBlock Grid.Row="4" Grid.Column="0" Grid.ColumnSpan="2" HorizontalAlignment="Center" VerticalAlignment="Center" Width="200" Margin="30,0,0,0" Text="{Binding Path=Order.Customer.FullName, Mode=TwoWay}"/>
<TextBlock Grid.Row="5" Grid.Column="0" Grid.ColumnSpan="2" HorizontalAlignment="Center" VerticalAlignment="Center" Width="200" Margin="30,0,0,0" Text="{Binding Path=Order.Product.ProductName, Mode=TwoWay}"/>
<TextBlock Grid.Row="6" Grid.Column="0" Grid.ColumnSpan="2" HorizontalAlignment="Center" VerticalAlignment="Center" Width="200" Margin="30,0,0,0" Text="{Binding Path=Order.Branch.BranchName, Mode=TwoWay}"/>
<TextBlock Grid.Row="7" Grid.Column="0" Grid.ColumnSpan="2" HorizontalAlignment="Center" VerticalAlignment="Center" Width="200" Margin="30,0,0,0" Text="{Binding Path=Order.SalesPrice, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}"/>
<TextBlock Grid.Row="8" Grid.Column="0" Grid.ColumnSpan="2" HorizontalAlignment="Center" VerticalAlignment="Center" Width="200" Margin="30,0,0,0" Text="{Binding Path=Order.Stocks, Mode=TwoWay}"/>
<Button Grid.Row="10" Grid.Column="0" Grid.ColumnSpan="2" HorizontalAlignment="Center" VerticalAlignment="Center" Width="60" Height="25" Content="Cancel" Command="{x:Static NavigationCommands.BrowseBack}" />
</Grid>
</Page>
Keep in mind that I've literally learned everything I know about data binding in the last 48 hours so bear with me here.
Any kind of help at all is very much appreciated. Thank!

You need to implement INotifyPropertyChanged in Orders class.
You need to Invoke OnPropertyChanged() inside all setters.

Where your view model is getting instantiated ? I guess since you are recreating your viewmodel instance in ModifyOrder class
boundData = new ViewModel();
binding is lost and may be because of that its not showing up .

...Yeah, so. It was the
public ViewModel()
{
Order = new Order();
}
that was wiping clean the private static Orders _Order in the ViewModel class every time it was instantiated so I changed it to
public ViewModel()
{
if (_Order == null)
{
Order = new Order();
}
}
and that fixed the problem...
Thanks to everyone that helped me out with this! I learned a lot from you all!
I'm going to go cry myself to sleep now <3

Related

Change color when selected on UWP C#

I need to change the color of a rectangle in a GridView when the item is selected.
Unselected item
Selected item
My Main Page in XAML.
<Page
x:Class="GridViewWithSelectedItem.Views.MainPage"
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:views="using:GridViewWithSelectedItem.Views"
Style="{StaticResource PageStyle}"
mc:Ignorable="d">
<Page.Resources>
<DataTemplate x:Key="TileTemplate" x:DataType="views:Article">
<Border BorderThickness="2,2,2,2" BorderBrush="#FF868484" Margin="3,3,3,3" HorizontalAlignment="Stretch" MaxWidth="600" MinWidth="525">
<Grid>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="10"/>
<ColumnDefinition/>
</Grid.ColumnDefinitions>
<Grid.RowDefinitions>
<RowDefinition/>
<RowDefinition Height="60"/>
<RowDefinition/>
</Grid.RowDefinitions>
<Rectangle Fill="Black" Grid.RowSpan="3"/>
<StackPanel Orientation="Horizontal" Grid.Row="0" Grid.Column="1">
<TextBlock FontSize="20" Margin="0,0,5,0" TextWrapping="Wrap" Foreground="DarkBlue" FontWeight="Bold" Text="{x:Bind Number}"/>
<TextBlock FontSize="20" TextWrapping="Wrap" Foreground="DarkBlue" Text="{x:Bind Title}" FontWeight="Bold"/>
</StackPanel>
<TextBlock Grid.Row="1" Grid.Column="1" FontSize="20" Text="{x:Bind Description}" TextWrapping="WrapWholeWords"/>
<StackPanel Background="LightBlue" Padding="5,0,0,0" Grid.Row="2" Grid.Column="1">
<StackPanel Orientation="Horizontal">
<TextBlock FontSize="20" Margin="0,0,5,0" TextWrapping="Wrap">Date :</TextBlock>
<TextBlock Foreground="Red" FontSize="20" TextWrapping="Wrap" Text="{x:Bind Date}" FontWeight="Bold"/>
</StackPanel>
</StackPanel>
</Grid>
</Border>
</DataTemplate>
</Page.Resources>
<Grid x:Name="ContentArea" Margin="{StaticResource MediumLeftRightMargin}">
<Grid Background="White" VerticalAlignment="Top" HorizontalAlignment="Stretch" Margin="0,25,0,0">
<Grid.ColumnDefinitions>
<ColumnDefinition Width="600"/>
<ColumnDefinition/>
</Grid.ColumnDefinitions>
<Grid.RowDefinitions>
<RowDefinition Height="60"/>
<RowDefinition Height="800"/>
</Grid.RowDefinitions>
<TextBlock Text="The Guardian" FontSize="35" FontWeight="Bold" Grid.ColumnSpan="2" HorizontalAlignment="Center"/>
<GridView
BorderThickness="2,2,0,2" BorderBrush="#FF868484"
MinWidth="600"
Grid.Column="0"
Grid.Row="1"
Padding="5,5,5,5"
HorizontalAlignment="Center"
CanDragItems="False"
IsItemClickEnabled="true"
IsTapEnabled="False"
IsSwipeEnabled="False"
ItemsSource="{x:Bind Articles}"
ItemTemplate="{StaticResource TileTemplate}"
SelectedItem="{x:Bind Mode=TwoWay, Path=SelectedArticle}"
/>
<RelativePanel Grid.Row="1" Grid.Column="1" Background="WhiteSmoke" BorderThickness="2" BorderBrush="#FF868484" Padding="10">
<Grid RelativePanel.AlignLeftWithPanel="True" RelativePanel.AlignRightWithPanel="True">
<Grid VerticalAlignment="Top">
<Grid.ColumnDefinitions>
<ColumnDefinition/>
</Grid.ColumnDefinitions>
<Grid.RowDefinitions>
<RowDefinition/>
<RowDefinition/>
</Grid.RowDefinitions>
<StackPanel Orientation="Horizontal" Grid.Row="0">
<TextBlock FontSize="20" Margin="0,0,5,0" TextWrapping="Wrap" Foreground="DarkBlue" FontWeight="Bold" Text="{x:Bind Path=SelectedArticle.Number, Mode=OneWay}"/>
<TextBlock FontSize="20" TextWrapping="Wrap" Foreground="DarkBlue" Text="{x:Bind Path=SelectedArticle.Title, Mode=OneWay}" FontWeight="Bold"/>
</StackPanel>
<TextBlock Grid.Row="1" FontSize="20" Text="{x:Bind Path=SelectedArticle.Description, Mode=OneWay}" TextWrapping="WrapWholeWords"/>
</Grid>
</Grid>
<RelativePanel Background="LightBlue" Padding="5,0,0,0" RelativePanel.AlignBottomWithPanel="True" RelativePanel.AlignLeftWithPanel="True" RelativePanel.AlignRightWithPanel="True">
<StackPanel Orientation="Horizontal">
<TextBlock FontSize="20" Margin="0,0,5,0" TextWrapping="Wrap">Date :</TextBlock>
<TextBlock Foreground="Red" FontSize="20" TextWrapping="Wrap" Text="{x:Bind Path=SelectedArticle.Date, Mode=OneWay}" FontWeight="Bold"/>
</StackPanel>
</RelativePanel>
</RelativePanel>
</Grid>
</Grid>
</Page>
And the class of my XAML Page.
using System;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Runtime.CompilerServices;
using Windows.UI.Xaml.Controls;
namespace GridViewWithSelectedItem.Views
{
public sealed partial class MainPage : Page, INotifyPropertyChanged
{
public ObservableCollection<Article> Articles;
private Article _selectedArticle;
public Article SelectedArticle
{
get { return _selectedArticle; }
set { Set(ref _selectedArticle, value); }
}
public MainPage()
{
InitializeComponent();
Articles = new ObservableCollection<Article>();
Articles.Add(new Article(0, "Uighurs", "Being young' leads to detention in China's Xinjiang region", DateTime.Parse("09/12/2020")));
Articles.Add(new Article(1, "Brexit", "Chances of Brexit deal hang on Boris Johnson and Ursula von der Leyen dinner", DateTime.Parse("09/12/2020")));
Articles.Add(new Article(2, "Environment", "Secretive ‘gold rush’ for deep-sea mining dominated by handful of firms", DateTime.Parse("09/12/2020")));
Articles.Add(new Article(3, "Juukan Gerge induiry", "Juukan Gorge inquiry: Rio Tinto's decision to blow up Indigenous rock shelters 'inexcusable'", DateTime.Parse("09/12/2020")));
Articles.Add(new Article(4, "Australia", "British journalist uncovered Australian woman's alleged plan to kill parents on dark web, police say", DateTime.Parse("09/12/2020")));
Articles.Add(new Article(5, "Coronavirus", "Nine out of 10 in poor nations to miss out on inoculation as west buys up Covid vaccines", DateTime.Parse("09/12/2020")));
}
public event PropertyChangedEventHandler PropertyChanged;
private void Set<T>(ref T storage, T value, [CallerMemberName]string propertyName = null)
{
if (Equals(storage, value))
{
return;
}
storage = value;
OnPropertyChanged(propertyName);
}
private void OnPropertyChanged(string propertyName) => PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
}
public class Article
{
public int Number { get; set; }
public string Title { get; set; }
public string Description { get; set; }
public DateTime Date { get; set; }
public Article(int number, string title, string description, DateTime date)
{
Number = number;
Title = title;
Description = description;
Date = Date;
}
}
}
I see AutomationProperty.name can help me but i don't understand how to use it.
I found a way to change the color of a selected item in my class but i need to recreate the collection and i cost lot of resources. I think its possible to make it in XAML code.
Edit: I made a simple exemple of my code.
OneDrive link
You could add a Brush property into the Article class, and bind the Brush property to Rectangle.Fill property of your DataTemplate to change the color when an item of GridView control is selected.
Please check the following code:
In DataTemplate of your xaml file:
<Rectangle x:Name="rectangle" Fill="{x:Bind Brush}" Grid.RowSpan="3"/>
……
<GridView …… SelectionChanged="GridView_SelectionChanged" />
In code-behind:
public class Article
{
……
public SolidColorBrush Brush { get; set; }
public Article(int number, string title, string description, DateTime date)
{
……
Brush = new SolidColorBrush(Colors.Black);
}
}
Add a _preSelectedArticle property to save the previous item in MainPage class:
private Article _preSelectedArticle;
Change the value of Brush property of selected item and previous selected item:
private void GridView_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
if(_preSelectedArticle==null)
{
SelectedArticle.Brush.Color = Colors.Green;
_preSelectedArticle = SelectedArticle;
}
if (_preSelectedArticle!=null&&_preSelectedArticle!= SelectedArticle)
{
_preSelectedArticle.Brush.Color = Colors.Black;
SelectedArticle.Brush.Color = Colors.Green;
_preSelectedArticle = SelectedArticle;
}
}

WPF MVVM properties binding not working properly

I have created a view model which has a single property for a student model, that I am then binding to a control in my XAML. But nothing is appearing when I execute the application.
I am setting data context in my app.xaml.cs as follows:
protected override void OnStartup(StartupEventArgs e)
{
base.OnStartup(e);
Registrationformusinemvvm.MainWindow window = new MainWindow();
VMUser VM = new VMUser();
window.DataContext = VM;
window.Show();
}
Why is the binding not working?
This is my view model:
public class VMUser:BaseClass
{
private student _currentStudent;
public student CurrentStudent
{
get { return _currentStudent; }
set {
_currentStudent = value;
OnPropertyChanged("CurrentStudent");
}
}
}
My Student model class:
public class student:BaseClass
{
private string name="sumit";
public string Name
{
get { return name; }
set { name = value; OnPropertyChanged("Name"); }
}
private int rollNum;
public int RollNum
{
get { return rollNum; }
set { rollNum = value;OnPropertyChanged("RollNum"); }
}
private int phNum;
public int PhNum
{
get { return phNum; }
set { phNum = value;OnPropertyChanged("PhNum"); }
}
private string sub;
public string Sub
{
get { return sub; }
set { sub = value;OnPropertyChanged("Sub"); }
}
}
My XAML:
<Window x:Class="Registrationformusinemvvm.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:local="clr-namespace:Registrationformusinemvvm"
xmlns:vm="clr-namespace:Registrationformusinemvvm.ViewModel"
mc:Ignorable="d"
Title="MainWindow" Height="350" Width="525">
<!--<Window.DataContext>
<vm:VMUser/>
</Window.DataContext>-->
<Window.Resources>
</Window.Resources>
<Grid>
<Grid.RowDefinitions>
<RowDefinition Height="50"/>
<RowDefinition Height="50"/>
<RowDefinition Height="50"/>
<RowDefinition Height="50"/>
<RowDefinition Height="50"/>
</Grid.RowDefinitions>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="200"/>
<ColumnDefinition Width="200"/>
<ColumnDefinition Width="*"/>
</Grid.ColumnDefinitions>
<TextBlock Text="Name" Grid.Column="0" Grid.Row="0" FontSize="14"
FontWeight="Bold" VerticalAlignment="Center"
HorizontalAlignment="Center"/>
<TextBlock Text="Roll Number" Grid.Column="0" Grid.Row="1" FontSize="14"
FontWeight="Bold" VerticalAlignment="Center"
HorizontalAlignment="Center"/>
<TextBlock Text="Subject" Grid.Column="0" Grid.Row="2" FontSize="14"
FontWeight="Bold" VerticalAlignment="Center"
HorizontalAlignment="Center"/>
<TextBlock Text="Phone Number" Grid.Column="0" Grid.Row="3"
FontSize="14" FontWeight="Bold" VerticalAlignment="Center"
HorizontalAlignment="Center"/>
<TextBox Name="tbName" Text="{Binding CurrentStudent.Name,Mode=TwoWay,
UpdateSourceTrigger=PropertyChanged}" Grid.Column="1" Grid.Row="0"
Width="120" Height="30" HorizontalAlignment="Center"
VerticalAlignment="Center"/>
<TextBox Name="tbRollnum" Text="{Binding CurrentStudent.RollNum}"
Grid.Column="1" Grid.Row="1" Width="120" Height="30"
HorizontalAlignment="Center" VerticalAlignment="Center"/>
<TextBox Name="tbSub" Text="{Binding CurrentStudent.Sub}"
Grid.Column="1" Grid.Row="2" Width="120" Height="30"
HorizontalAlignment="Center" VerticalAlignment="Center"/>
<TextBox Name="tbPh" Text="{Binding CurrentStudent.PhNum}"
Grid.Column="1" Grid.Row="3" Width="120" Height="30"
HorizontalAlignment="Center" VerticalAlignment="Center"/>
<Button Name="tbSubmit" Content="Submit" Grid.ColumnSpan="3"
Grid.Row="4" Height="30" Width="100" HorizontalAlignment="Center"/>
</Grid>
</Window>
My guess is that your binding isn't working because your _currentStudent is null by default. Initialize your _currentStudent if null.
public student CurrentStudent
{
get { return _currentStudent = (_currentStudent ?? new student()); }
set
{
_currentStudent = value; OnPropertyChanged("CurrentStudent");
}
}
You need to add OnPropertyChanged in your model class.
void OnPropertyChanged(string prop)
{
if (this.PropertyChanged != null)
this.PropertyChanged(this, new PropertyChangedEventArgs(prop));
}
public event PropertyChangedEventHandler PropertyChanged;
As per your above code you cant assigned the value to CurrentStudent Property so
can you please check do you have the value to CurrentStudent property.
Thank you for your question
Remove StartupUri="YourXamlFile.xaml" from App.Xaml

Is not updated selected item on listview (wpf mvvm) if field of item changed

I'm writing my first program with the use wpf and mvvm.
Have a problem, that in the case of changes data in fields of selecteditem, selecting a new item becomes impossible.
If add to listview attribute SelectionMode="Single", then if many times try pick item, exeption:
The element with the same key has already been added.
image: https://www.dropbox.com/s/ey7izl19803uuhc/1.png
If this attribute is removed, then pick another item, simply does not occur.
Image: https://dl.dropboxusercontent.com/u/32438899/2.png
If the data has not changed, the navigation works fine.
XAML code:
<?xml version="1.0" encoding="utf-8" ?>
<Window x:Class="MHConfigurator.Views.MainView"
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:DataContext="{Binding Path=MainViewModel}"
Title="Редактирование шаблонов писем" Height="Auto" Width="1000" MinWidth="1000" MinHeight="400">
<Grid>
<Grid.RowDefinitions>
<RowDefinition Height="Auto"></RowDefinition>
<RowDefinition></RowDefinition>
<RowDefinition Height="Auto"></RowDefinition>
</Grid.RowDefinitions>
<DockPanel Grid.Row="0" Margin="7">
<TextBlock DockPanel.Dock="Left" Margin="5,5,2,5" HorizontalAlignment="Left">Поиск:</TextBlock>
<TextBox DockPanel.Dock="Right" Margin="2,2,2,2" HorizontalAlignment="Stretch" Text="{Binding SearchString, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}"></TextBox>
</DockPanel>
<ListView Grid.Row="1" ItemsSource="{Binding Path=MailProperties, Mode=TwoWay}" Width="Auto" HorizontalAlignment="Stretch"
VerticalAlignment="Stretch" Margin="5" SelectedItem="{Binding Path=CurrentProperty, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}" >
<ListView.View>
<GridView>
<GridViewColumn DisplayMemberBinding="{Binding ButtonID, Mode=TwoWay}" Header="ID шаблона" Width="Auto" />
<GridViewColumn DisplayMemberBinding="{Binding Description, Mode=TwoWay}" Header="Описание" Width="Auto" />
</GridView>
</ListView.View>
</ListView>
<Grid VerticalAlignment="Center" Grid.Row="2" DataContext="{Binding CurrentProperty}">
<Grid.ColumnDefinitions>
<ColumnDefinition Width="250"></ColumnDefinition>
<ColumnDefinition></ColumnDefinition>
</Grid.ColumnDefinitions>
<Grid.RowDefinitions>
<RowDefinition Height="*"></RowDefinition>
<RowDefinition Height="*"></RowDefinition>
<RowDefinition Height="*"></RowDefinition>
<RowDefinition Height="*"></RowDefinition>
<RowDefinition Height="*"></RowDefinition>
<RowDefinition Height="*"></RowDefinition>
<RowDefinition Height="*"></RowDefinition>
<RowDefinition Height="*"></RowDefinition>
</Grid.RowDefinitions>
<DockPanel Grid.Row="0" Grid.Column="0">
<TextBlock DockPanel.Dock="Left" Margin="5,5,2,5" VerticalAlignment="Center" HorizontalAlignment="Left">ID шаблона:</TextBlock>
<TextBox DockPanel.Dock="Right" Margin="2,2,2,2" VerticalAlignment="Center" HorizontalAlignment="Stretch"
VerticalContentAlignment="Center" Text="{Binding ButtonID}"></TextBox>
</DockPanel>
<DockPanel Grid.Row="1" Grid.Column="0">
<CheckBox DockPanel.Dock="Left" HorizontalAlignment="Left" Margin="5" VerticalAlignment="Center" IsChecked="{Binding FillSubject}">Заполнять тему</CheckBox>
</DockPanel>
<DockPanel Grid.Row="2" Grid.Column="0">
<CheckBox DockPanel.Dock="Left" HorizontalAlignment="Left" Margin="5" VerticalAlignment="Center" IsChecked="{Binding FillTO}">Заполнять адресатов</CheckBox>
</DockPanel>
<DockPanel Grid.Row="3" Grid.Column="0">
<CheckBox DockPanel.Dock="Left" HorizontalAlignment="Left" Margin="5" VerticalAlignment="Center" IsChecked="{Binding FillCopy}">Заполнять копию</CheckBox>
</DockPanel>
<DockPanel Grid.Row="4" Grid.Column="0">
<CheckBox DockPanel.Dock="Left" HorizontalAlignment="Left" Margin="5" VerticalAlignment="Center" IsChecked="{Binding FillHideCopy}">Заполнять скрытую копию</CheckBox>
</DockPanel>
<DockPanel Grid.Row="5" Grid.Column="0">
<CheckBox DockPanel.Dock="Left" HorizontalAlignment="Left" Margin="5" VerticalAlignment="Center" IsChecked="{Binding HighImportance}">Высокая важность</CheckBox>
</DockPanel>
<DockPanel Grid.Row="0" Grid.Column="1">
<TextBlock DockPanel.Dock="Left" VerticalAlignment="Center" Margin="10,5,2,5" Width="115" >Описание шаблона:</TextBlock>
<TextBox DockPanel.Dock="Left" Margin="2,2,5,2" TextWrapping="Wrap" VerticalContentAlignment="Center" Text="{Binding Description}"></TextBox>
</DockPanel>
<DockPanel Grid.Row="1" Grid.Column="1">
<TextBlock DockPanel.Dock="Left" VerticalAlignment="Center" Margin="10,5,2,5" Width="115">Тема письма:</TextBlock>
<TextBox DockPanel.Dock="Left" Margin="2,2,5,2" TextWrapping="Wrap" VerticalContentAlignment="Center" Text="{Binding Subject}"></TextBox>
</DockPanel>
<DockPanel Grid.Row="2" Grid.Column="1">
<TextBlock DockPanel.Dock="Left" VerticalAlignment="Center" Margin="10,5,2,5" Width="115">Адресаты:</TextBlock>
<TextBox DockPanel.Dock="Left" Margin="2,2,5,2" TextWrapping="Wrap" VerticalContentAlignment="Center" Text="{Binding TO}"></TextBox>
</DockPanel>
<DockPanel Grid.Row="3" Grid.Column="1">
<TextBlock DockPanel.Dock="Left" VerticalAlignment="Center" Margin="10,5,2,5" Width="115">Копия:</TextBlock>
<TextBox DockPanel.Dock="Left" Margin="2,2,5,2" TextWrapping="Wrap" VerticalContentAlignment="Center" Text="{Binding Copy}"></TextBox>
</DockPanel>
<DockPanel Grid.Row="4" Grid.Column="1">
<TextBlock DockPanel.Dock="Left" VerticalAlignment="Center" Margin="10,5,2,5" Width="115">Скрытая копия:</TextBlock>
<TextBox DockPanel.Dock="Left" Margin="2,2,5,2" TextWrapping="Wrap" VerticalContentAlignment="Center" Text="{Binding HideCopy}"></TextBox>
</DockPanel>
<DockPanel Grid.Row="5" Grid.Column="1">
<CheckBox DockPanel.Dock="Left" VerticalAlignment="Center" HorizontalAlignment="Center" Margin="5">Напоминание</CheckBox>
<TextBlock DockPanel.Dock="Left" VerticalAlignment="Center" Margin="4">Время напоминания:</TextBlock>
<TextBox DockPanel.Dock="Left" Margin="2,2,5,2" VerticalContentAlignment="Center"></TextBox>
</DockPanel>
<DockPanel Grid.Row="6" Grid.Column="1">
<CheckBox DockPanel.Dock="Left" VerticalAlignment="Center" HorizontalAlignment="Left" Margin="5">Заполнять текст письма</CheckBox>
</DockPanel>
<DockPanel Grid.Row="7" Grid.Column="0" Grid.ColumnSpan="2">
<Button DockPanel.Dock="Left" Margin="15" HorizontalAlignment="Left" VerticalAlignment="Center" Width="150" Height="40">Добавить новый шаблон</Button>
<Button DockPanel.Dock="Left" Margin="15" HorizontalAlignment="Left" VerticalAlignment="Center" Width="150" Height="40">Сохранить</Button>
<Button DockPanel.Dock="Left" Margin="15" HorizontalAlignment="Left" VerticalAlignment="Center" Width="150" Height="40">Отмена</Button>
<TextBlock DockPanel.Dock="Left" Margin="0,4,4,4" VerticalAlignment="Center">Заметка:</TextBlock>
<TextBox DockPanel.Dock="Right" Margin="5" TextWrapping="Wrap" AcceptsReturn="True" Height="70" HorizontalAlignment="Stretch" VerticalScrollBarVisibility="Visible"
SpellCheck.IsEnabled="True" Language="ru-ru"></TextBox>
</DockPanel>
</Grid>
</Grid>
</Window>
In viewmodel problems can not be. It is very easy, PropertyChanged called whenever necessary.
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Collections.Specialized;
using System.ComponentModel;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using MugenMvvmToolkit;
using MugenMvvmToolkit.ViewModels;
using MugenMvvmToolkit.Models;
using System.Windows.Input;
using MHConfigurator.Models;
using System.Windows;
namespace MHConfigurator.ViewModels
{
class MainViewModel : ViewModelBase
{
public MainViewModel()
{
_mailProperties = new ObservableCollection<MailProperty>(DAL.GetDAL().MailPropertys);
//MailsTemplates = DAL.GetDAL().GetEmptyMailTemplates();
}
#region Fields
#region Backing Fields
private ObservableCollection<MailProperty> _mailProperties;
private MailProperty _currentProperty;
private string _searchString;
private MailProperty _originalCurrentProperty;
private bool _currentPropertyChanged = false;
private List<MailsTemplate> _mailsTemplates;
private int _selectedMailTemplate;
#endregion
public string SearchString
{
get
{
if (_searchString.IsNullOrEmpty()) return "";
return _searchString;
}
set
{
bool stringContains = _searchString != null && value.Contains(_searchString);
_searchString = value;
CurrentProperty = null;
//Not matter
}
}
public ObservableCollection<MailProperty> MailProperties
{
get { return _mailProperties; }
set
{
_mailProperties = value;
//OnPropertyChanged(new PropertyChangedEventArgs("MailProperties"));
OnPropertyChanged();
}
}
public MailProperty CurrentProperty
{
get { return _currentProperty; }
set
{/*
if ((_originalCurrentProperty != null)&&(_currentPropertyChanged)&&(_originalCurrentProperty!=_currentProperty)) //Если выбран другой объект и есть несохранённые изменения
{
MessageBoxResult result = MessageBox.Show("Есть несохранённые изменения. Сохранить?", "Несохранённые изменения", MessageBoxButton.YesNo, MessageBoxImage.Question);
if (result == MessageBoxResult.Yes)
{
}
else
{
MailProperties[MailProperties.IndexOf(_currentProperty)] = _originalCurrentProperty; //Находим в коллекции изменённый объект и заменить его оригиналом
}
}
_originalCurrentProperty = Helper.DeepClone(_currentProperty); //Делаем резервную копию
SelectedMailTemplate = value.BodyID; //выставляем id шаблона
*/
_currentProperty = value;
// OnPropertyChanged(new PropertyChangedEventArgs("CurrentProperty"));
OnPropertyChanged();
}
}
public List<MailsTemplate> MailsTemplates
{
get { return _mailsTemplates; }
set
{
_mailsTemplates = value;
OnPropertyChanged();
}
}
public int SelectedMailTemplate
{
get { return _selectedMailTemplate; }
set
{
_selectedMailTemplate = value;
CurrentProperty.BodyID = value;
OnPropertyChanged();
}
}
#endregion
#region Commands
public ICommand NewCommand { get; private set; }
public ICommand SaveCommand { get; private set; }
public ICommand CancelCommand { get; private set; }
#region Execute
#endregion
#region CanExecute
#endregion
#endregion
}}
I have no idea.
I will be glad to any ideas.
P.S.: Sorry for my bad english.

UWP buttons inside Listview items

I'm working on my first UWP app and I want create a UI like this . For each list item (project) there'll be a set of buttons. For certain list items(projects) some of these buttons will be disabled some times. So I need to disable and change the image for such button in those list items(projects).
I tried to implement it using a list view like this. But I am not sure how I can enable/disable some of those buttons depending on the condition.
Tried adding a DataContextChanged event and trying to access the buttons there. But not sure how I can access those buttons.
Please let me know whether the following approach is correct or is there a better way to do what I am trying to achieve in the above image.
<ListView x:Name="stepsListView" Margin="10,0,0,0" RequestedTheme="Dark" FontSize="24" Background="{StaticResource procedure_app_white}" Foreground="Black" BorderThickness="1.5" BorderBrush="Transparent" ItemsSource="{Binding projectList}" HorizontalAlignment="Left">
<ListView.ItemContainerStyle>
<Style TargetType="ListViewItem">
<Setter Property="HorizontalContentAlignment" Value="Stretch"/>
</Style>
</ListView.ItemContainerStyle>
<!-- Item -->
<ListView.ItemTemplate>
<DataTemplate>
<Border BorderThickness="0,0,0,1" BorderBrush="#c0c0c0">
<Grid Width="auto" HorizontalAlignment="Stretch" DataContextChanged="Grid_DataContextChanged" >
<Grid.RowDefinitions>
<RowDefinition Height="*"/>
<RowDefinition Height="50"/>
</Grid.RowDefinitions>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="*"/>
<ColumnDefinition Width="100"/>
<ColumnDefinition Width="100"/>
<ColumnDefinition Width="100"/>
<ColumnDefinition Width="100"/>
<ColumnDefinition Width="100"/>
<ColumnDefinition Width="100"/>
</Grid.ColumnDefinitions>
<TextBlock VerticalAlignment="Center" FontSize="30" Grid.Row="0" Grid.ColumnSpan="7" Text="{Binding projectName}" Foreground="{StaticResource procedure_app_orange_text }" />
<Button x:Name="warningButton" Width="40" Height="40" Grid.Column="1" Grid.Row="1" Tag="{Binding projectId}" Click="warningButtonClick" Foreground="{StaticResource procedure_app_orange_text }">
<Button.Background>
<ImageBrush ImageSource="Asset/step_ncwr.png">
</ImageBrush>
</Button.Background>
</Button>
<Button x:Name="commentButton" Width="40" Height="40" Grid.Column="2" Grid.Row="1" Tag="{Binding projectId}" Click="CommentButtonClick" Foreground="{StaticResource procedure_app_orange_text }" IsTapEnabled="True">
<Button.Background>
<ImageBrush ImageSource="Asset/step_comment.png">
</ImageBrush>
</Button.Background>
</Button>
<Button x:Name="imageButton" Width="40" Height="40" Grid.Column="3" Grid.Row="1" Tag="{Binding projectId}" Click="ImageButtonClick" Foreground="{StaticResource procedure_app_orange_text }">
<Button.Background>
<ImageBrush ImageSource="Asset/step_image.png">
</ImageBrush>
</Button.Background>
</Button>
</Grid>
</Border>
</DataTemplate>
</ListView.ItemTemplate>
The answer is to variable dependent on what structure you've gone with so I am going to make some assumptions and roll with it.
First I am going to assume your ViewModel has an ObservableCollection called ProjectList and that this ProjectList is made up of ProjectModel's
ProjectModel.cs
public class ProjectModel : INotifyPropertyChanged{
private bool _isNcwrEnabled;
public bool IsNcwrEnabled{
get{ return _isNcwrEnabled; }
set{ _isNcwrEnabled = value; OnPropertyChanged("IsNcwrEnabled"); }
}
private bool _isCommentEnabled;
public bool IsCommentEnabled{
get{ return _isCommentEnabled; }
set{ _isCommentEnabled= value; OnPropertyChanged("IsCommentEnabled"); }
}
private bool _isImageEnabled;
public bool IsImageEnabled{
get{ return _isImageEnabled; }
set{ _isImageEnabled= value; OnPropertyChanged("IsImageEnabled"); }
}
public void OnPropertyChanged(String prop)
{
PropertyChangedEventHandler handler = PropertyChanged;
if (handler != null)
{
PropertyChanged(this, new PropertyChangedEventArgs(prop));
}
}
public event PropertyChangedEventHandler PropertyChanged;
}
In your ViewModel you should have
ObservableCollection<ProjectModel> ProjectList {get; private set; }
Finally in your View
<Button IsEnabled="{Binding IsNcwrEnabled}" x:Name="warningButton" Width="40" Height="40" Grid.Column="1"
Grid.Row="1" Tag="{Binding projectId}" Click="warningButtonClick"
Foreground="{StaticResource procedure_app_orange_text }">
<Button.Background>
<ImageBrush ImageSource="Asset/step_ncwr.png"/>
</Button.Background>
</Button>
<Button IsEnabled="{Binding IsCommentEnabled}" x:Name="commentButton" Width="40" Height="40" Grid.Column="2"
Grid.Row="1" Tag="{Binding projectId}" Click="CommentButtonClick"
Foreground="{StaticResource procedure_app_orange_text }" IsTapEnabled="True">
<Button.Background>
<ImageBrush ImageSource="Asset/step_comment.png"/>
</Button.Background>
</Button>
<Button IsEnabled="{Binding IsImageEnabled}" x:Name="imageButton" Width="40" Height="40" Grid.Column="3"
Grid.Row="1" Tag="{Binding projectId}" Click="ImageButtonClick"
Foreground="{StaticResource procedure_app_orange_text }">
<Button.Background>
<ImageBrush ImageSource="Asset/step_image.png"/>
</Button.Background>
</Button>
Summary of Changes
The models in the collection that your ListView is bound to needs to contain enabled properties for your Buttons to bind to
In your View, bind your Buttons to your new properties

WPF display content based on treeview selected item

I was able to retrieve selected item value from my treeview. Now I want to change the content in ScrollViewer control based on that value. I'm trying to display property values of Facility object which contains Containments which contains Tanks.
I'm new to programming sorry if my explanation is not clear enough.
Thank you.
MyWindow.xaml
<Window.DataContext>
<local:VisioFacilityExportViewModel/>
</Window.DataContext>
<Window.Resources>
<DataTemplate x:Key="FacilityTemplate">
<Grid>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="Auto"/>
<ColumnDefinition Width="200"/>
</Grid.ColumnDefinitions>
<Grid.RowDefinitions>
<RowDefinition Height="30"/>
<RowDefinition Height="30"/>
<RowDefinition Height="30"/>
<RowDefinition Height="30"/>
<RowDefinition Height="30"/>
<RowDefinition Height="30"/>
<RowDefinition Height="30"/>
<RowDefinition Height="30"/>
<RowDefinition Height="30"/>
<RowDefinition Height="30"/>
<RowDefinition Height="30"/>
<RowDefinition Height="30"/>
<RowDefinition Height="30"/>
<RowDefinition Height="30"/>
<RowDefinition Height="30"/>
<RowDefinition Height="30"/>
<RowDefinition Height="30"/>
<RowDefinition Height="30"/>
<RowDefinition Height="30"/>
<RowDefinition Height="30"/>
</Grid.RowDefinitions>
<Label Content="Facility ID:"/>
<TextBox Grid.Row="0" Grid.Column="1" Height="20" Text="{Binding ListFacilities[0].FacilityID}"/>
<Label Content="Address:" Grid.Row="1"/>
<TextBox Grid.Row="1" Grid.Column="1" Height="20" Text="{Binding ListFacilities[0].Address}"/>
<Label Content="Description:" Grid.Row="2"/>
<TextBox Grid.Row="2" Grid.Column="1" Height="20" Text="{Binding ListFacilities[0].Description}"/>
<Label Content="Layout And Drainage:" Grid.Row="3"/>
<TextBox Grid.Row="3" Grid.Column="1" Height="20" Text="{Binding ListFacilities[0].LayoutAndDrainage}"/>
<Label Content="Latitude:" Grid.Row="4"/>
<TextBox Grid.Row="4" Grid.Column="1" Height="20" Text="{Binding ListFacilities[0].Latitude}"/>
<Label Content="Longitude:" Grid.Row="5"/>
<TextBox Grid.Row="5" Grid.Column="1" Height="20" Text="{Binding ListFacilities[0].Longitude}"/>
<Label Content="City:" Grid.Row="6"/>
<TextBox Grid.Row="6" Grid.Column="1" Height="20" Text="{Binding ListFacilities[0].City.Name}"/>
<Label Content="County:" Grid.Row="7"/>
<TextBox Grid.Row="7" Grid.Column="1" Height="20" Text="{Binding ListFacilities[0].County.Name}"/>
<Label Content="Name:" Grid.Row="8"/>
<TextBox Grid.Row="8" Grid.Column="1" Height="20" Text="{Binding ListFacilities[0].Name}"/>
<Label Content="Run:" Grid.Row="9"/>
<TextBox Grid.Row="9" Grid.Column="1" Height="20" Text="{Binding ListFacilities[0].Run}"/>
<Label Content="Surface Flow Direction:" Grid.Row="10"/>
<TextBox Grid.Row="10" Grid.Column="1" Height="20" Text="{Binding ListFacilities[0].SurfaceFlowDirection}"/>
<Label Content="API Number:" Grid.Row="11"/>
<TextBox Grid.Row="11" Grid.Column="1" Height="20" Text="{Binding ListFacilities[0].APINumber}"/>
<Label Content="Distance To Navigable Waters:" Grid.Row="12"/>
<TextBox Grid.Row="12" Grid.Column="1" Height="20" Text="{Binding ListFacilities[0].DistanceToNavigableWaters}"/>
<Label Content="Project Phase:" Grid.Row="13"/>
<TextBox Grid.Row="13" Grid.Column="1" Height="20" Text="{Binding ListFacilities[0].APINumber}"/>
<Label Content="Unique ID:" Grid.Row="14"/>
<TextBox Grid.Row="14" Grid.Column="1" Height="20" Text="{Binding ListFacilities[0].UniqueID}"/>
<Label Content="Operational Field:" Grid.Row="15"/>
<TextBox Grid.Row="15" Grid.Column="1" Height="20" Text="{Binding ListFacilities[0].OperationalField}"/>
<Label Content="Facility Type:" Grid.Row="16"/>
<TextBox Grid.Row="16" Grid.Column="1" Height="20" Text="{Binding ListFacilities[0].FacilityType}"/>
<Label Content="Project Number:" Grid.Row="17"/>
<TextBox Grid.Row="17" Grid.Column="1" Height="20" Text="{Binding ListFacilities[0].ProjectNumber}"/>
<Label Content="Project Phase:" Grid.Row="18"/>
<TextBox Grid.Row="18" Grid.Column="1" Height="20" Text="{Binding ListFacilities[0].ProjectPhase}"/>
<Label Content="Report Number:" Grid.Row="19"/>
<TextBox Grid.Row="19" Grid.Column="1" Height="20" Text="{Binding ListFacilities[0].ReportNumber}"/>
</Grid>
</DataTemplate>
<DataTemplate x:Key="ContainmentTemplate">
<Grid>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="Auto"/>
<ColumnDefinition Width="200"/>
</Grid.ColumnDefinitions>
<Grid.RowDefinitions>
<RowDefinition Height="30"/>
<RowDefinition Height="30"/>
<RowDefinition Height="30"/>
<RowDefinition Height="30"/>
<RowDefinition Height="30"/>
<RowDefinition Height="30"/>
<RowDefinition Height="30"/>
<RowDefinition Height="30"/>
<RowDefinition Height="30"/>
<RowDefinition Height="30"/>
<RowDefinition Height="30"/>
</Grid.RowDefinitions>
<Label Content="Name:"/>
<TextBox Grid.Column="1" Height="20" Text="{Binding ListContainments[0].Name}"/>
<Label Content="Height:" Grid.Row="1"/>
<TextBox Grid.Row="1" Grid.Column="1" Height="20" Text="{Binding ListContainments[0].Height}"/>
<Label Content="Diameter:" Grid.Row="2"/>
<TextBox Grid.Row="2" Grid.Column="1" Height="20" Text="{Binding ListContainments[0].TankPadHeight}"/>
<Label Content="County:" Grid.Row="3"/>
<TextBox Grid.Row="3" Grid.Column="1" Height="20" Text="{Binding ListContainments[0].TankPadWidth}"/>
<Label Content="Inner Length:" Grid.Row="4"/>
<TextBox Grid.Row="4" Grid.Column="1" Height="20" Text="{Binding ListContainments[0].TankPadLength}"/>
<Label Content="Inner Width:" Grid.Row="5"/>
<TextBox Grid.Row="5" Grid.Column="1" Height="20" Text="{Binding ListContainments[0].InnerLength}"/>
<Label Content="Top Length:" Grid.Row="6"/>
<TextBox Grid.Row="6" Grid.Column="1" Height="20" Text="{Binding ListContainments[0].InnerWidth}"/>
<Label Content="Top Width:" Grid.Row="7"/>
<TextBox Grid.Row="7" Grid.Column="1" Height="20" Text="{Binding ListContainments[0].TopLength}"/>
<Label Content="Construction:" Grid.Row="8"/>
<TextBox Grid.Row="8" Grid.Column="1" Height="20" Text="{Binding ListContainments[0].TopWidth}"/>
<Label Content="Fill Materials:" Grid.Row="9"/>
<TextBox Grid.Row="9" Grid.Column="1" Height="20" Text="{Binding ListContainments[0].Construction}"/>
<Label Content="Fill Material Height (Top):" Grid.Row="10"/>
<TextBox Grid.Row="10" Grid.Column="1" Height="20" Text="{Binding ListContainments[0].Diameter}"/>
</Grid>
</DataTemplate>
<DataTemplate x:Key="TanksTemplate">
<Grid>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="Auto"/>
<ColumnDefinition Width="200"/>
</Grid.ColumnDefinitions>
<Grid.RowDefinitions>
<RowDefinition Height="30"/>
<RowDefinition Height="30"/>
<RowDefinition Height="30"/>
<RowDefinition Height="30"/>
<RowDefinition Height="30"/>
<RowDefinition Height="30"/>
<RowDefinition Height="30"/>
<RowDefinition Height="30"/>
<RowDefinition Height="30"/>
<RowDefinition Height="30"/>
<RowDefinition Height="30"/>
<RowDefinition Height="30"/>
</Grid.RowDefinitions>
<Label Content="Name:"/>
<TextBox Grid.Column="1" Height="20" Text="{Binding ListTanks[0].Name}"/>
<Label Content="Height:" Grid.Row="1"/>
<TextBox Grid.Row="1" Grid.Column="1" Height="20" Text="{Binding ListTanks[0].Height}"/>
<Label Content="Diameter:" Grid.Row="2"/>
<TextBox Grid.Row="2" Grid.Column="1" Height="20" Text="{Binding ListTanks[0].Diameter}"/>
<Label Content="Is in Service:" Grid.Row="3"/>
<TextBox Grid.Row="3" Grid.Column="1" Height="20" Text="{Binding ListTanks[0].IsInService}"/>
<Label Content="Is on Pad:" Grid.Row="4"/>
<CheckBox Grid.Row="4" Grid.Column="1" Height="20" IsChecked="{Binding ListTanks[0].IsOnPad}"/>
<Label Content="Contents:" Grid.Row="5"/>
<TextBox Grid.Row="5" Grid.Column="1" Height="20" Text="{Binding ListTanks[0].Contents}"/>
<Label Content="Year Constructed:" Grid.Row="6"/>
<TextBox Grid.Row="6" Grid.Column="1" Height="20" Text="{Binding ListTanks[0].YearConstructed}"/>
<Label Content="Material:" Grid.Row="7"/>
<TextBox Grid.Row="7" Grid.Column="1" Height="20" Text="{Binding ListTanks[0].Material}"/>
<Label Content="Is Portable:" Grid.Row="8"/>
<CheckBox Grid.Row="8" Grid.Column="1" Height="20" IsChecked="{Binding ListTanks[0].IsPortable}"/>
<Label Content="Is Isolated:" Grid.Row="9"/>
<CheckBox Grid.Row="9" Grid.Column="1" Height="20" IsChecked="{Binding ListTanks[0].IsIsolated}"/>
<Label Content="Quantity:" Grid.Row="10"/>
<TextBox Grid.Row="10" Grid.Column="1" Height="20" Text="{Binding ListTanks[0].Quantity}"/>
<Label Content="Orientation:" Grid.Row="11"/>
</Grid>
</DataTemplate>
</Window.Resources>
<Grid Margin="5" Height="Auto">
<Grid.ColumnDefinitions>
<ColumnDefinition Width="Auto"/>
<ColumnDefinition Width="*"/>
</Grid.ColumnDefinitions>
<Grid.RowDefinitions>
<RowDefinition Height="*"/>
<RowDefinition Height="30"/>
</Grid.RowDefinitions>
<TreeView Name="trvFacility" ItemsSource="{Binding MenuItems}" VirtualizingStackPanel.IsVirtualizing="True" Padding="10" Margin="5" Width="220">
<i:Interaction.Behaviors>
<local:BindableSelectedItemBehavior SelectedItem="{Binding SelectedItem,Mode=TwoWay}"/>
</i:Interaction.Behaviors>
<TreeView.ItemTemplate>
<HierarchicalDataTemplate ItemsSource="{Binding Children}" DataType="{x:Type entities:MenuItemCust}">
<TextBlock Text="{Binding Name}"/>
</HierarchicalDataTemplate>
</TreeView.ItemTemplate>
</TreeView>
<ScrollViewer Grid.Row="0" Grid.Column="1" Margin="5" VerticalScrollBarVisibility="Visible">
DataTemplate here
</ScrollViewer>
<Button Content="Save" Grid.Row="1" Grid.ColumnSpan="2" Grid.Column="0" Width="60" Height="25" Margin="0,0,5,0" HorizontalAlignment="Right"/>
</Grid>
MyWindowViewModel.cs
public class VisioFacilityExportViewModel : INotifyPropertyChanged
{
public VisioFacilityExportViewModel()
{
_lstFacilities = new ObservableCollection<Facility>(DatabaseHandler.GetFacilities().Where(f => f.FacilityID == 2015012314001933));
_lstContainments = _lstFacilities[0].Containment;
_lstTanks = _lstContainments[0].Tanks;
List<MenuItemCust> lstRoot = new List<MenuItemCust>();
List<MenuItemCust> lstContainment = new List<MenuItemCust>();
List<MenuItemCust> lstTanks = new List<MenuItemCust>();
MenuItems = new List<MenuItemCust>();
foreach (var f in _lstFacilities)
{
foreach (var c in f.Containment)
{
lstTanks.AddRange(c.Tanks.Select(t => new MenuItemCust { Name = t.Name, Info = "Tanks"}));
lstContainment.Add(new MenuItemCust { Name = c.Name, Children = lstTanks, Info = "Containment" });
}
lstRoot.Add(new MenuItemCust { Name = "Containment", Children = lstContainment, Info = "Facility"});
MenuItems.Add(new MenuItemCust { Name = "Facility", Children = lstRoot });
}
}
private ObservableCollection<Tank> _lstTanks;
public ObservableCollection<Tank> ListTanks
{
get { return _lstTanks; }
set
{
_lstTanks = value;
NotifyPropertyChanged("ListTanks");
}
}
private ObservableCollection<Containment> _lstContainments;
public ObservableCollection<Containment> ListContainments
{
get { return _lstContainments; }
set
{
_lstContainments = value;
NotifyPropertyChanged("ListContainments");
}
}
private ObservableCollection<Facility> _lstFacilities;
public ObservableCollection<Facility> ListFacilities
{
get { return _lstFacilities; }
set
{
_lstFacilities = value;
NotifyPropertyChanged("ListFacilities");
}
}
private List<MenuItemCust> _menuItems;
public List<MenuItemCust> MenuItems
{
get { return _menuItems; }
set
{
_menuItems = value;
NotifyPropertyChanged("MenuItems");
}
}
private static object _selectedItem = null;
public static object SelectedItem
{
get { return _selectedItem; }
private set
{
if (_selectedItem != value)
{
_selectedItem = value;
OnSelectedItemChanged();
}
}
}
public static void OnSelectedItemChanged()
{
var item = (MenuItemCust) SelectedItem;
if (item.Name == "Facility")
{
}
else if (item.Info == "Containment")
{
}
else if (item.Info == "Tanks")
{
}
}
#region iNotifyPropertyChanged
public event PropertyChangedEventHandler PropertyChanged;
protected virtual void NotifyPropertyChanged(string property)
{
if (PropertyChanged != null)
PropertyChanged(this, new PropertyChangedEventArgs(property));
}
#endregion
}
I think what you want to do is display informations in a UserControl which will contains a grid with differents controls like textblock and textbox.
So you are going to create a new UserControl named FacilityView and FacilityViewModel and the FacilityView will contains a grid with ur Facility Ojbect property
First of all, I would create an property in MyWindowViewModel called
private Facility currentFacility;
public Facility CurrentFacility
{
get{return currentFacility;}
set{ currentFacility = value ;
notifyPropertyChange("CurrentFacility")
}
In your MainWindowsView (xaml)
<DataTemplate DataType="{x:Type localAdder:FacilityViewModel}">
<localAdder:FacilityView />
</DataTemplate>
<UserControl Grid.Row="1" Grid.Column="2"
Content="{Binding CurrentFacility,Mode=TwoWay,UpdateSourceTrigger=PropertyChanged,NotifyOnSourceUpdated=True}">
</UserControl>
And in your SelectedItem you would
if (selectedItem is Facility)
{
CurrentFacility = new FacilityViewModel(selectedItem as Facility);
}
Sry for the bad indentation im not use to this writing code.
EDIT2:
Okay, you have 2 choice, first of all u can create a BaseViewModel which will implements INotifyPropertyChanged.
FacilityViewModel : BaseViewModel
TankViewModel : BaseViewModel
ContainmentViewModel : BaseViewModel
This way you will change CurrentFacilityViewModel to CurrentBaseViewModel
private BaseViewModel currentBaseXXX;
public BaseViewModel CurrentBaseXXX
{
get{return currentBaseXXX;}
set{ currentBaseXXX= value ;
notifyPropertyChange("CurrentBaseXXX")
}
And in your SelectedItem you would
if (selectedItem is Facility)
{
CurrentBaseXXX= new FacilityViewModel(selectedItem as Facility);
}
if (selectedItem is Tank)
{
CurrentBaseXXX= new TankViewModel(selectedItem as Tank);
}
if (selectedItem is Containers)
{
CurrentBaseXXX= new ContainersViewModel(selectedItem as Containers);
}
Options2
You would have 3 current so
CurrentFacilityVM
CurrentTankVM
CurrentContainerVM
And in your SelectedItem you would
CurrentFacilityVM = null;
CurrentTankVM =null;
CurrentContainerVM =null;
if (selectedItem is Facility)
{
CurrentFacilityVM = new FacilityViewModel(selectedItem as Facility);
}
if (selectedItem is Tank)
{
CurrentTankVM = new TankViewModel(selectedItem as Tank);
}
if (selectedItem is Containers)
{
CurrentContainerVM = new ContainersViewModel(selectedItem as Containers);
}
You can dynamically Load the data template based on Type. Refer the below. You can toggle the template by change the instance of the SelectedItem to a Different class.
<Window.Resources>
<DataTemplate DataType="{x:Type entities:Facility}">
<Grid>
<TextBlock Text="{Binding FacilityName}" />
</Grid>
</DataTemplate>
<DataTemplate DataType="{x:Type entities:Containment}">
<Grid>
<TextBlock Text="{Binding ContainmentName}"/>
</Grid>
</DataTemplate>
<DataTemplate DataType="{x:Type entities:Tank}">
<Grid>
<TextBlock Text="{Binding TankName}"></TextBlock>
</Grid>
</DataTemplate>
</Window.Resources>
<Grid Margin="5" Height="Auto">
<Grid.ColumnDefinitions>
<ColumnDefinition Width="Auto"/>
<ColumnDefinition Width="*"/>
</Grid.ColumnDefinitions>
<Grid.RowDefinitions>
<RowDefinition Height="*"/>
<RowDefinition Height="30"/>
</Grid.RowDefinitions>
<ScrollViewer Grid.Row="0" Grid.Column="1" Margin="5" VerticalScrollBarVisibility="Visible" DataContext="{Binding SelectedItem}">
<ContentControl Content="{Binding }"/>
</ScrollViewer>
<Button Content="Save" Grid.Row="1" Grid.ColumnSpan="2" Grid.Column="0" Width="60" Height="25" Margin="0,0,5,0" HorizontalAlignment="Right"/>
</Grid>
public partial class Download : Window
{
public Download()
{
InitializeComponent();
this.DataContext = new VisioFacilityExportViewModel();
}
}
public class VisioFacilityExportViewModel : INotifyPropertyChanged
{
public VisioFacilityExportViewModel()
{
//SelectedItem = new Facility() { FacilityName = "Facility" };
//SelectedItem = new Tank() { TankName = "Tank" };
SelectedItem = new Containment() { ContainmentName = "Containment" };
}
private object _selectedItem = null;
public object SelectedItem
{
get { return _selectedItem; }
private set
{
if (_selectedItem != value)
{
_selectedItem = value;
NotifyPropertyChanged("SelectedItem");
}
}
}
#region iNotifyPropertyChanged
public event PropertyChangedEventHandler PropertyChanged;
protected virtual void NotifyPropertyChanged(string property)
{
if (PropertyChanged != null)
PropertyChanged(this, new PropertyChangedEventArgs(property));
}
#endregion
}
public class Tank
{
private string myVar;
public string TankName
{
get { return myVar; }
set { myVar = value; }
}
}
class Facility
{
private string myVar;
public string FacilityName
{
get { return myVar; }
set { myVar = value; }
}
}
class Containment
{
private string myVar;
public string ContainmentName
{
get { return myVar; }
set { myVar = value; }
}
}

Categories