Please see the XAML below:
<?xml version="1.0" encoding="utf-8" ?>
<ContentPage xmlns="http://xamarin.com/schemas/2014/forms"
xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
xmlns:local="clr-namespace:App1"
x:Class="App1.MainPage">
<ContentPage.BindingContext>
<local:PersonViewModel />
</ContentPage.BindingContext>
<StackLayout>
<Grid>
<Grid.ColumnDefinitions>
<ColumnDefinition />
<ColumnDefinition />
<ColumnDefinition />
</Grid.ColumnDefinitions>
<Grid.RowDefinitions>
<RowDefinition Height="20" />
</Grid.RowDefinitions>
<Label Grid.Column="1" Text="First Name" />
<Label Grid.Column="2" Text="Surname" />
<Label Grid.Column="3" Text="Date Of Birth" />
</Grid>
<ListView x:Name="listView" ItemsSource="{Binding people}">
<ListView.ItemTemplate>
<DataTemplate>
<ViewCell>
<Grid>
<Label Grid.Column="1" Text="{Binding FirstName}" />
<Label Grid.Column="2" Text="{Binding Surname}" />
<Label Grid.Column="3" Text="{Binding Age}" />
</Grid>
</ViewCell>
</DataTemplate>
</ListView.ItemTemplate>
</ListView>
</StackLayout>
</ContentPage>
and the View Model:
public class PersonViewModel
{
public ObservableCollection<Person> people = new ObservableCollection<Person>();
public PersonViewModel()
{
people.Add(new Person { Age = 36, FirstName = "Andrew", Surname = "Smith" });
people.Add(new Person { Age = 65, FirstName = "David", Surname = "White" });
people.Add(new Person { Age = 39, FirstName = "Bert", Surname = "Edwards" });
}
}
Only the column headings display. Why does the data not display?
I have spent all afternoon trying to get this to work. I have read lots of different answers, however I still cannot get any data to display.
You are missing the Grid Column Definitions (if it is the same as the header, so your xaml should look like this:
<StackLayout>
<Grid>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="* />
<ColumnDefinition Width="* />
<ColumnDefinition Width="* />
</Grid.ColumnDefinitions>
<Grid.RowDefinitions>
<RowDefinition Height="20" />
</Grid.RowDefinitions>
<Label Grid.Column="1" Text="First Name" />
<Label Grid.Column="2" Text="Surname" />
<Label Grid.Column="3" Text="Date Of Birth" />
</Grid>
<ListView x:Name="listView" ItemsSource="{Binding people}">
<ListView.ItemTemplate>
<DataTemplate>
<ViewCell>
<Grid>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="* />
<ColumnDefinition Width="* />
<ColumnDefinition Width="* />
</Grid.ColumnDefinitions>
<Label Grid.Column="1" Text="{Binding FirstName}" />
<Label Grid.Column="2" Text="{Binding Surname}" />
<Label Grid.Column="3" Text="{Binding Age}" />
</Grid>
</ViewCell>
</DataTemplate>
</ListView.ItemTemplate>
</ListView>
</StackLayout>
Related
I have a Content Page in which I want to show an invoice, for that I have two listviews.
The first one contains the name of the customer, the date and the total cost.
The thing is to get the total cost I have used Shell navigation with parameters and it works fine just not in the listview.
So here is my ViewModel
[QueryProperty(nameof(Total), "total")]
public class InvoiceViewModel : BindableObject
{
string _total;
public string Total
{
get => _total;
set
{
_total = Uri.UnescapeDataString(value ?? string.Empty);
OnPropertyChanged();
}
}
public InvoiceViewModel()
{
_oListOrders = new ObservableCollection<CrOrder>();
GetListCart();
}
private ApiService _apiService = new ApiService();
public List<Invoice> _oListCart = new List<Invoice>();
public ObservableCollection<CrOrder> _oListOrders;
public List<Invoice> ListCart
{
get => _oListCart;
set
{
_oListCart = value;
OnPropertyChanged();
}
}
private async void GetListCart()
{
// call database here
var customerId = Convert.ToInt32(CurrentPropertiesService.GetCustomer());
var customer = await _apiService.GetCustomerById(customerId, CurrentPropertiesService.GetToken());
_oListCart.Add(new Invoice
{
Name = customer.Data.Name,
Date = DateTime.UtcNow,
Total = Convert.ToDecimal(_total),
ListOrders = await GetListOrders()
});
}
private async Task<ObservableCollection<CrOrder>> GetListOrders()
{
// call database here
var cartId = Convert.ToInt32(CurrentPropertiesService.GetCart());
var orders = await _apiService.GetOrdersByCart(cartId, CurrentPropertiesService.GetToken());
ObservableCollection<CrOrder> collection = new ObservableCollection<CrOrder>(orders.Data);
return collection;
}
}
Here is what I have in my View
<ContentPage.Content>
<StackLayout BackgroundColor="#A7A7A7">
<Label Text="{Binding Total}" VerticalOptions="CenterAndExpand" HorizontalOptions="CenterAndExpand"></Label>
<ListView x:Name="ListViewCart" ItemsSource="{Binding ListCart}" HasUnevenRows="True" IsPullToRefreshEnabled="False" >
<ListView.ItemTemplate>
<DataTemplate x:DataType="model:Invoice">
<ViewCell>
<Frame HasShadow="True" Margin="2" BorderColor="Gray">
<Grid Margin="0" HorizontalOptions="FillAndExpand" VerticalOptions="Center" HeightRequest="150" RowSpacing="0" ColumnSpacing="0">
<Grid.RowDefinitions>
<RowDefinition Height="auto"/>
<RowDefinition Height="auto"/>
<RowDefinition Height="auto"/>
<RowDefinition Height="auto"/>
<RowDefinition Height="auto"/>
<RowDefinition Height="auto"/>
<RowDefinition Height="auto"/>
</Grid.RowDefinitions>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="5*"/>
<ColumnDefinition Width="3*"/>
<ColumnDefinition Width="2*"/>
</Grid.ColumnDefinitions>
<Label Grid.Row="0" Grid.Column="0" Text="Nombre del Cliente:" VerticalOptions="Start"/>
<Label Grid.Row="0" Grid.Column="1" Grid.ColumnSpan="2" Text="{Binding Name}" VerticalOptions="Start"/>
<Label Grid.Row="1" Grid.Column="0" Text="Fecha Compra:" VerticalOptions="Start"/>
<Label Grid.Row="1" Grid.Column="1" Grid.ColumnSpan="2" Text="{Binding Date}" VerticalOptions="Start"/>
<Label Grid.Row="2" Grid.Column="0" Text="Monto Total:" VerticalOptions="Start"/>
<Label Grid.Row="2" Grid.Column="1" Grid.ColumnSpan="2" Text="{Binding Total, StringFormat='{0:N2}€'}" VerticalOptions="Start"/>
<Label Grid.Row="3" Grid.ColumnSpan="3" Text="Detalle Compra" VerticalOptions="Start"/>
<BoxView Grid.Row="4" Grid.ColumnSpan="3" Color="Gray" HeightRequest="2" HorizontalOptions="Fill" />
<Label Grid.Row="5" Grid.Column="0" Text="Nombre" VerticalOptions="Start" TextColor="#9C2424"/>
<Label Grid.Row="5" Grid.Column="1" Text="Monto" VerticalOptions="Start" TextColor="#9C2424"/>
<Label Grid.Row="5" Grid.Column="2" Text="Cantidad" VerticalOptions="Start" TextColor="#9C2424"/>
<StackLayout Grid.Row="6" Grid.ColumnSpan="3" Margin="0" Padding="0">
<ListView x:Name="ListViewOrders" ItemsSource="{Binding ListOrders}" HasUnevenRows="True" IsPullToRefreshEnabled="False" >
<ListView.ItemTemplate>
<DataTemplate x:DataType="model:CrOrder">
<ViewCell IsEnabled="False">
<Grid RowSpacing="0" ColumnSpacing="0" Margin="0" MinimumHeightRequest="50">
<Grid.ColumnDefinitions>
<ColumnDefinition Width="5*"/>
<ColumnDefinition Width="3*"/>
<ColumnDefinition Width="2*"/>
</Grid.ColumnDefinitions>
<Grid.RowDefinitions>
<RowDefinition/>
</Grid.RowDefinitions>
<Label Grid.Row="0" Grid.Column="0" Text="{Binding Reference}" TextColor="Black" VerticalOptions="Center" FontSize="12" />
<Label Grid.Row="0" Grid.Column="1" Text="{Binding Price, StringFormat='{0:N2}€'}" TextColor="Black" VerticalOptions="End" FontSize="12" />
<Label Grid.Row="0" Grid.Column="2" Text="{Binding Quantity}" TextColor="Black" VerticalOptions="End" FontSize="12"/>
</Grid>
</ViewCell>
</DataTemplate>
</ListView.ItemTemplate>
</ListView>...
And on my ContentPage I don't have anything
[XamlCompilation(XamlCompilationOptions.Compile)]
public partial class InvoicePage : ContentPage
{
public InvoicePage()
{
InitializeComponent();
//BindingContext = new InvoiceViewModel();
}
}
So on my View I have put a label to check what I thought was happening. So the label shows right the total but when I use the ListView binging it doesn't work I don't know why it is null there.
As you can see the label works fine but where it sais "Monto Total" it shows nothing. Please help I don't know what is going on. Thanks.
EDIT
I tried naming the Total property different and then when I add my Invoice entity to my list I do this
Total = Convert.ToDecimal(TotalCart),
But it isn't working eitherway. I don't know why the first time it returns the value fine but the second it doesn't.
After debbuging I have realized when getting the total property that the first time when GetListCart is being called the value is null and the second time, when the label text is set it returns the correct value. Why is this happening?
In Xamarin forms with MVVM ; I'm using observable collection for listing my items in the listview. It worked fine. In my listview i have a Label and i need to change the Label value when the user click on that selected list item. It's also working fine. But the problem is, Selected list item Label value changed only after i scroll the listview.
I need to change the selected list item's Label value On time.
Here is my code:
Xaml
<ListView x:Name="Listitem" Grid.Row="2" Grid.ColumnSpan="2" ItemsSource="{Binding States,Mode=TwoWay}" SelectedItem="{Binding YourSelectedItem,Mode=TwoWay}" VerticalOptions="FillAndExpand" HasUnevenRows="true" CachingStrategy="RecycleElement" BackgroundColor="White" >
<ListView.Header>
<Grid BackgroundColor="{StaticResource Accent}">
<Grid.ColumnDefinitions>
<ColumnDefinition Width="*" />
<ColumnDefinition Width="*" />
<ColumnDefinition Width="*" />
</Grid.ColumnDefinitions>
<Label Grid.Column="0" Text="Country Code" HorizontalOptions="Center" VerticalOptions="Center" TextColor="{StaticResource Primary}" />
<Label Grid.Column="1" Text="Name" HorizontalOptions="Center" TextColor="{StaticResource Primary}" />
<Label Grid.Column="2" Text="Capital" HorizontalOptions="Center" TextColor="{StaticResource Primary}" />
</Grid>
</ListView.Header>
<ListView.ItemTemplate>
<DataTemplate>
<ViewCell>
<ViewCell.View>
<Grid VerticalOptions="Center">
<Grid.ColumnDefinitions>
<ColumnDefinition Width="3*" />
<ColumnDefinition Width="3*" />
<ColumnDefinition Width="3*" />
<ColumnDefinition Width="1*" />
</Grid.ColumnDefinitions>
<Label Grid.Column="0" Text="{Binding abbr}" Margin="5" HorizontalOptions="Center" VerticalOptions="Center" FontSize="18" TextColor="{StaticResource Primary}" />
<Label Grid.Column="1" Text="{Binding name}" Margin="5" HorizontalTextAlignment="Start" VerticalOptions="Center" FontSize="18" LineBreakMode="WordWrap" TextColor="{StaticResource Primary}"/>
<Label Grid.Column="2" Text="{Binding capital}" Margin="5" HorizontalTextAlignment="Start" VerticalOptions="Center" FontSize="18" LineBreakMode="WordWrap" TextColor="{StaticResource Primary}"/>
<controls:CheckBox Grid.Column="3" Margin="0, 0, 0, 0" CheckedChanged="Handle_CheckedChanged" BindingContext="{Binding .}" BackgroundColor="Transparent" WidthRequest="40" HeightRequest="30" IsVisible="True" />
</Grid>
</ViewCell.View>
</ViewCell>
</DataTemplate>
</ListView.ItemTemplate>
</ListView>
And this is my View model for selected list item;
public TodoItem YourSelectedItem
{
get
{
return _yourSelectedItem;
}
set
{
_yourSelectedItem = value;
_yourSelectedItem.abbr = "Tapped";
OnPropertyChanged("YourSelectedItem");
}
}
Item source property;
private ObservableCollection<TodoItem> _States;
public ObservableCollection<TodoItem> States
{
get { return _States; }
set { _States = value; OnPropertyChanged("States"); }
}
The class TodoItem needs to implement the interface INotifyPropertyChanged and the property abbr needs to be implemented as something like blow:
public string abbr {
get
{
return _abbr;
}
set
{
if (_abbr != value) {
_abbr = value;
OnPropertyChanged("abbr");
}
}
}
I put a ListView and a Label, immediately after it, but on screen, there is a Empty space between the ListView and the Label with the Text ms.
I would like the ListView to expand automatically, when the items are present.
Or is there an ItemsControl, like WPF?
I have this XAML:
<?xml version="1.0" encoding="utf-8" ?>
<ContentPage xmlns="http://xamarin.com/schemas/2014/forms"
xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
xmlns:local="clr-namespace:Forms"
x:Class="Forms.MainPage">
<ContentPage.Resources>
<ResourceDictionary>
<local:MyConverter x:Key="MyConverter"></local:MyConverter>
</ResourceDictionary>
</ContentPage.Resources>
<ScrollView Orientation="Vertical">
<StackLayout Padding="10,10,10,10">
<Label FontSize="20" FontAttributes="Bold">Cartão de Ponto</Label>
<Label>Nome:</Label>
<Label Text="{Binding Path=Pessoa.Nome}" />
<Label>CPF:</Label>
<Label Text="{Binding Path=Pessoa.CPF}" />
<Grid Padding="0" MinimumHeightRequest="40">
<Grid.ColumnDefinitions>
<ColumnDefinition Width="70" />
<ColumnDefinition Width="35" />
<ColumnDefinition Width="60" />
<ColumnDefinition Width="60" />
<ColumnDefinition Width="60" />
</Grid.ColumnDefinitions>
<Label FontSize="10" Text="Data" FontAttributes="Bold" VerticalTextAlignment="End" />
<Label FontSize="10" Grid.Column="1" Text="Dia" FontAttributes="Bold" VerticalTextAlignment="End" />
<Label FontSize="10" Grid.Column="2" Text="Hora Entrada" FontAttributes="Bold" VerticalTextAlignment="End" />
<Label FontSize="10" Grid.Column="3" Text="Hora Saída" FontAttributes="Bold" VerticalTextAlignment="End" />
<Label FontSize="10" Grid.Column="4" Text="Horas Trabalhadas" HorizontalTextAlignment="End" FontAttributes="Bold" />
</Grid>
<!-- HeightRequest="0"-->
<ListView x:Name="lv1" ItemsSource="{Binding Path=Pontos}"
VerticalOptions="FillAndExpand"
HasUnevenRows="False"
>
<ListView.Header>
<StackLayout HeightRequest="0" />
</ListView.Header>
<!-- ItemTemplate -->
<ListView.Footer>
<StackLayout HeightRequest="0" />
</ListView.Footer>
<ListView.ItemTemplate>
<DataTemplate>
<ViewCell>
<ViewCell.View>
<Grid>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="70" />
<ColumnDefinition Width="35" />
<ColumnDefinition Width="60" />
<ColumnDefinition Width="60" />
<ColumnDefinition Width="60" />
</Grid.ColumnDefinitions>
<Label FontSize="12" Text="{Binding Path=Data, StringFormat='{0:dd/MM/yyyy}'}" />
<Label FontSize="12" Grid.Column="1" Text="{Binding Path=DiaSemana}" />
<Label FontSize="12" Grid.Column="2" Text="{Binding Path=HoraEntrada}" />
<Label FontSize="12" Grid.Column="3" Text="{Binding Path=HoraSaida}" />
<Label FontSize="12" Grid.Column="4" Text="{Binding Path=HorasTrabalhadas, Converter={StaticResource MyConverter}}}" />
</Grid>
</ViewCell.View>
</ViewCell>
</DataTemplate>
</ListView.ItemTemplate>
</ListView>
<!-- Why is this White space on screen? -->
<StackLayout Orientation="Horizontal">
<Label x:Name="lbl1" />
<Label>ms</Label>
</StackLayout>
<Button x:Name="ButtonPegaCartaoPonto" Text="Carregar" />
<Label></Label>
<Label></Label>
</StackLayout>
</ScrollView>
</ContentPage>
But the ListView lv1 does not automatically expand Horizontally to fit the Items.
How to do this?
Set RowHeight property of your ListView and update height of list using code behind in your constructor like this:
lv1.PropertyChanged += (object sender, System.ComponentModel.PropertyChangedEventArgs e) =>
{
if (e.PropertyName == "ItemsSource")
{
try
{
if (lv1.ItemsSource != null)
{
var tmp = (IList) lv1.ItemsSource;
lv1.HeightRequest = tmp.Count * lv1.RowHeight;
}
}
catch (Exception ex)
{
}
}
};
OR
You can also put specific heigh based on row height.
lv1.PropertyChanged += (object sender, System.ComponentModel.PropertyChangedEventArgs e) =>
{
if (e.PropertyName == "ItemsSource")
{
try
{
if (lv1.ItemsSource != null)
{
var tmp = (IList) lv1.ItemsSource;
lv1.HeightRequest = tmp.Count * 40;
}
}
catch (Exception ex)
{
}
}
};
I will be able to deselect my item when i click second time on it.
When I tap an item the background color changed to blue. I want that the background gets the default color when I tap second time to the same item from the list.
Here can you find my code but it isn't working.
XAML
<StackLayout Margin="5,0,5,0" HorizontalOptions="FillAndExpand" VerticalOptions="CenterAndExpand">
<Frame Style="{StaticResource StandardFrameStyle}" HorizontalOptions="FillAndExpand" VerticalOptions="FillAndExpand">
<ListView x:Name="lst_pickList" ItemSelected="OnItemSelected" ItemTapped="OnItemTapped" ItemsSource="{Binding PickList}" HasUnevenRows="True" Style="{StaticResource StandardListViewStyle}">
<ListView.ItemTemplate>
<DataTemplate>
<ViewCell>
<ViewCell.View>
<Grid x:Name="grd_pickList" HorizontalOptions="FillAndExpand" VerticalOptions="FillAndExpand" >
<Grid.RowDefinitions>
<RowDefinition Height="Auto" />
<RowDefinition Height="Auto" />
</Grid.RowDefinitions>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="*" />
<ColumnDefinition Width="*" />
<ColumnDefinition Width="*" />
<ColumnDefinition Width="*" />
</Grid.ColumnDefinitions>
<Label x:Name="lbl_comment" Text="Comment:" FontAttributes="Bold" Grid.Row="0" Grid.Column="0" VerticalTextAlignment="Center" Style="{StaticResource StandardLabelStyle}" />
<Label x:Name="lbl_itemNo" Text="ItemNo:" FontAttributes="Bold" Grid.Row="0" Grid.Column="2" VerticalTextAlignment="Center" Style="{StaticResource StandardLabelStyle}" />
<Label x:Name="lbl_description" Text="Description:" FontAttributes="Bold" Grid.Row="1" Grid.Column="0" VerticalTextAlignment="Center" Style="{StaticResource StandardLabelStyle}" />
<Label x:Name="lbl_restant" Text="Restant:" FontAttributes="Bold" Grid.Row="1" Grid.Column="2" VerticalTextAlignment="Center" Style="{StaticResource StandardLabelStyle}" />
<Label x:Name="lbl_comment_binding" Text="{Binding Comment}" Grid.Row="0" Grid.Column="1" VerticalTextAlignment="Center" Style="{StaticResource StandardLabelStyle}" />
<Label x:Name="lbl_itemNo_binding" Text="{Binding ItemNo}" Grid.Row="0" Grid.Column="3" VerticalTextAlignment="Center" Style="{StaticResource StandardLabelStyle}" />
<Label x:Name="lbl_description_binding" Text="{Binding Description}" Grid.Row="1" Grid.Column="1" VerticalTextAlignment="Center" Style="{StaticResource StandardLabelStyle}" />
<Label x:Name="lbl_restant_binding" Text="{Binding Restant}" Grid.Row="1" Grid.Column="3" VerticalTextAlignment="Center" Style="{StaticResource StandardLabelStyle}" />
</Grid>
</ViewCell.View>
</ViewCell>
</DataTemplate>
</ListView.ItemTemplate>
</ListView>
</Frame>
</StackLayout>
CodeBehind
public void OnItemTapped(object sender, ItemTappedEventArgs args)
{
var newSelectedPick = args.Item as Pick;
if(selectedPick != null && selectedPick.Id == newSelectedPick.Id)
{
lst_pickList.SelectedItem = null;
}
else
{
selectedPick = newSelectedPick;
}
}
Create a boolean property on your Pick object named IsSelected ,then Bind it your grd_pickList's BackgroundColor with a converter.
i.e:
//Xaml
<ListView.Resources>
<ResourceDictionary>
<local:BgConverter x:Key="BgConverter"/>
</ResourceDictionary>
</ListView.Resources>
<Grid x:Name="grd_pickList" HorizontalOptions="FillAndExpand" VerticalOptions="FillAndExpand" BackgroundColor="{Binding IsSelected,Converter={StaticResource BgConverter}}" >
//Converter
class BgConverter : IValueConverter
{
public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
{
if (value is bool &&(bool)value)
return Color.Blue;
else
return Color.White;
}
public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
{
throw new NotSupportedException();
}
}
//Xaml.cs
public void OnItemTapped(object sender, ItemTappedEventArgs args)
{
var itm = args.Item as Pick;
itm.IsSelected = !itm.IsSelected;
}
Important: Be Sure IsSelected Property Triggers OnPropertyChanged event.
My itemscontrol is currently loading each row correctly. I am trying to get it to change the background color of each row when the user selects it.
<Grid>
<Grid.RowDefinitions>
<RowDefinition Height="100" />
<RowDefinition Height="30" />
<RowDefinition Height="*" />
</Grid.RowDefinitions>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="*" />
</Grid.ColumnDefinitions>
<Grid Grid.Row="0">
<Border BorderBrush="#BBBDBF" Background="#F4F4F4" BorderThickness="0,1,0,1" Margin="10,10,10,10"/>
<Image HorizontalAlignment="Left" Margin="10,0,0,0" Height="38" Width="38" Source="C:\Users\linda_l\Pictures\Cloud upload\database (1).png" />
<TextBlock FontSize="50" Foreground="#4092C2" Margin="60,0,0,0" HorizontalAlignment="left" Height="69" >Databases</TextBlock>
</Grid>
<Grid Background="White" Grid.Row="1">
<Grid.ColumnDefinitions>
<ColumnDefinition Width="10" />
<ColumnDefinition Width="*" />
<ColumnDefinition Width="*" />
<ColumnDefinition Width="*" />
<ColumnDefinition Width="70" />
<ColumnDefinition Width="10" />
</Grid.ColumnDefinitions>
<Border BorderBrush="#BBBDBF" BorderThickness="0,0,0,1" Grid.Column="1" />
<Label Grid.Column="1" Content="Server Name" VerticalAlignment="Bottom" FontWeight="Bold" Foreground="#4092C2" />
<Border BorderBrush="#BBBDBF" BorderThickness="1,0,0,1" Grid.Column="2" />
<Label Grid.Column="2" Content="Source Database" VerticalAlignment="Bottom" FontWeight="Bold" Foreground="#4092C2" />
<Border BorderBrush="#BBBDBF" BorderThickness="1,0,0,1" Grid.Column="3" />
<Label Grid.Column="3" Content="Destination Database" VerticalAlignment="Bottom" FontWeight="Bold" Foreground="#4092C2" />
<Border BorderBrush="#BBBDBF" BorderThickness="1,0,0,1" Grid.Column="4" />
<Label Grid.Column="4" Content="Status" VerticalAlignment="Bottom" FontWeight="Bold" Foreground="#4092C2" />
</Grid>
<ItemsControl x:Name="itemscntrl" ItemsSource="{Binding DatabaseServers}" Background="White" BorderBrush="WhiteSmoke" BorderThickness="0" Grid.Row="2" Margin="0,5,0,0">
<ItemsControl.ItemTemplate>
<DataTemplate>
<Grid x:Name="grd" Background="White" >
<Grid.ColumnDefinitions>
<ColumnDefinition Width="10" />
<ColumnDefinition Width="*" />
<ColumnDefinition Width="*" />
<ColumnDefinition Width="*" />
<ColumnDefinition Width="70" />
<ColumnDefinition Width="10" />
</Grid.ColumnDefinitions>
<Image Source="{Binding StatusImage}" Height="10" Width="10" />
<Label Grid.Column="1" HorizontalAlignment="Left" Content="{Binding ServerName}" />
<Label Grid.Column="2" HorizontalAlignment="Left" Content="{Binding SourceDatabase}" />
<TextBox x:Name="dst" Grid.Column="3" Text="{Binding DestinationDatabase , Mode=TwoWay, UpdateSourceTrigger=LostFocus}" VerticalAlignment="Top" />
<Label Grid.Column="4" Content="{Binding Status}" VerticalAlignment="Top" />
<Button Grid.Column="4" BorderThickness="0" HorizontalAlignment="Center" Width="50" Margin="3" Content="{Binding Status}" Command="{Binding EnabledCommand}" CommandParameter="{Binding}" />
</Grid>
<DataTemplate.Triggers>
<DataTrigger Binding="{Binding selected }" Value="True">
<Setter Property="Background" Value="Yellow" TargetName="dst" />
</DataTrigger>
</DataTemplate.Triggers>
</DataTemplate>
</ItemsControl.ItemTemplate>
</ItemsControl>
</Grid>
Which currently looks like this:
I tried adding a DataTemplate.Triggers but it doesn't seam to do anything. How exactly do you detect that a row in a itemscontrol has been selected? The only examples I have found use a datagrid. I tried changing mine to a datagrid instead of the itemscontrol, but then the it wouldn't load the data.
Datagrid:
<DataGrid x:Name="grd" Background="White" DataContext="{Binding DatabaseServers}" Grid.Row="2">
<Image Source="{Binding StatusImage}" Height="10" Width="10" />
<Label Grid.Column="1" HorizontalAlignment="Left" Content="{Binding ServerName}" />
<Label Grid.Column="2" HorizontalAlignment="Left" Content="{Binding SourceDatabase}" />
<TextBox x:Name="dst" Grid.Column="3" Text="{Binding DestinationDatabase , Mode=TwoWay, UpdateSourceTrigger=LostFocus}" VerticalAlignment="Top" />
<Label Grid.Column="4" Content="{Binding Status}" VerticalAlignment="Top" />
<Button Grid.Column="4" BorderThickness="0" HorizontalAlignment="Center" Width="50" Margin="3" Content="{Binding Status}" Command="{Binding EnabledCommand}" CommandParameter="{Binding}" />
</DataGrid>
Just shows a bunch of lines there is no data in each row.
I am very new to WPF so I cant really figure out what I am doing wrong here.
Here is what you want using DataGrid i m using MVVM
Window.xaml
<Grid Margin="10">
<StackPanel Orientation="Vertical">
<Label Content="DataBases" Width="150" Height="50" HorizontalAlignment="Left" FontSize="20"/>
<DataGrid Name="DgDataSource" AutoGenerateColumns="False" CanUserAddRows="False" ItemsSource="{Binding SourceData}">
<DataGrid.Columns>
<DataGridTextColumn Header="ServerName" Binding="{Binding ServerName}" Width="2*"/>
<DataGridTextColumn Header="SourceDatabase" Binding="{Binding SourceDatabase}" Width="2*"/>
<DataGridTextColumn Header="DestinationDatabase" Binding="{Binding DestinationDatabase}" Width="2*"/>
<DataGridTemplateColumn Width="*" Header="Status" >
<DataGridTemplateColumn.CellTemplate>
<DataTemplate>
<Button Content="{Binding Status}" Command="{Binding EnabledCommand}"></Button>
</DataTemplate>
</DataGridTemplateColumn.CellTemplate>
</DataGridTemplateColumn>
</DataGrid.Columns>
</DataGrid>
</StackPanel>
</Grid>
View Model
public class WindowViewModel
{
public ObservableCollection<DataSource> SourceData { get; set; }
public WindowViewModel()
{
Initialize();
}
private void Initialize()
{
SourceData = new ObservableCollection<DataSource>
{
new DataSource() {Status = "Stop", ServerName = "Test 1", SourceDatabase = "Unknown",DestinationDatabase = "blabla....."},
new DataSource() {Status = "Work", ServerName = "Test 2", SourceDatabase = "Unknown",DestinationDatabase = "blabla....."},
new DataSource() {Status = "Stop", ServerName = "Test 3", SourceDatabase = "Unknown",DestinationDatabase = "blabla....."}
};
}
}
Model
public class DataSource
{
public string Status { get; set; }
public string ServerName { get; set; }
public string SourceDatabase { get; set; }
public string DestinationDatabase { get; set; }
}