Using WPF template in codebehind - c#

I have this template:
<DataTemplate x:Key="currencyColumn">
<StackPanel Height="210" Margin="0,0,0,0" VerticalAlignment="Top" Width="64" ScrollViewer.VerticalScrollBarVisibility="Disabled">
<Image Height="64" Source="assets/images/chaos.png"/>
<TextBox x:Name="total" Height="24" TextWrapping="Wrap" Text="{Binding Total}" HorizontalContentAlignment="Center" VerticalContentAlignment="Center" Width="48" FontSize="16" FontWeight="Bold" Margin="0,10,0,0" IsReadOnly="True"/>
<TextBox x:Name="used" Height="24" TextWrapping="Wrap" HorizontalContentAlignment="Center" VerticalContentAlignment="Center" Width="48" FontWeight="Bold" FontSize="16" Margin="0,10,0,0"/>
<TextBox x:Name="payed" Height="24" TextWrapping="Wrap" HorizontalContentAlignment="Center" VerticalContentAlignment="Center" Width="48" FontWeight="Bold" FontSize="16" Margin="0,10,0,0"/>
<TextBox x:Name="owed" Height="24" TextWrapping="Wrap" Text="{Binding Owed}" HorizontalContentAlignment="Center" VerticalContentAlignment="Center" Width="48" FontWeight="Bold" FontSize="16" Margin="0,10,0,0" IsReadOnly="True"/>
</StackPanel>
</DataTemplate>
What i want to do is to add to a ListBoxan undefined number of times this template at runtime via codebehind, each with the source of the image modified and i would like to bind the textbox with readonly tag to some variables.

I do not see a point to bind this through code behind, when you can do it just directly in the View(xaml).
I suppose you have a certain model to show this data in your UI:
public class MyModel
{
public string ImageSource {get;set;}
public double Total {get;set;}
public double Used {get;set;}
public double Paid {get;set;}
public double Owed {get;set;}
}
In your VM, you would have a collection of this, since you said you will have a undefined number of them.
using Prism.Mvvm;
public class MyVM : BindableBase
{
public ObservableCollection<MyModel> MyModelCollection
{
get {return _myModelCollection;}
set {SetProperty(ref _myModelCollection);}
}
private ObservableCollection<MyModel> _myModelCollection;
}
Lastly, in your View (xaml)
<ItemsControl ItemsSource="{Binding MyModelCollection, Mode=OneWay}"
ItemTemplate="{StaticResource currencyColumn}">
</ItemsControl>
Here I am using your already defined DataTemplate.

Related

MVVM WPF Add new item to the DataGrid from Textboxes which are bound to the nested properties of the Model class

I am new to WPF and also the MVVM pattern, I tried to create a simple WPF project to query a database of I-Shape Steel Profiles and show it to the user through the DataGrid. After I have successfully done it, I am now moving to the next part: Letting the user to add new steel profiles to the DataGrid by filling out a set of TextBoxes.
Model
namespace SectionGuardWPF.MVVM.Model
{
public class IProfileModel : ObservableObject
{
#region Private Fields
public short _recno;
public string _name;
public string _staadName;
public double _ax;
public double _d;
public double _bf;
public double _tf;
public double _tw;
public double _iz;
public double _ix;
public double _ct;
public double _iy;
public double _zx;
public double _zy;
#endregion
#region Public Properties
/// <summary>
/// Properties are given NotifyPropertyChanged method to allow for a change in property to be notified
/// </summary>
public short RECNO
{
get { return _recno; }
set
{
_recno = value;
OnPropertyChanged();
}
}
public string Name
{
get { return _name; }
set
{
_name = value;
OnPropertyChanged();
}
}
...
// Repeated for the other fields
ObservableObject: Base class that implements INotifyPropertyChanged
namespace SectionGuardWPF.Core
{
public class ObservableObject : INotifyPropertyChanged
{
/// <summary>
/// Raised when a property on this object has a new value.
/// </summary>
public event PropertyChangedEventHandler PropertyChanged;
/// <summary>
/// Raises this object's PropertyChanged event.
/// </summary>
protected void OnPropertyChanged([CallerMemberName] string name = null) // If you use the CallerMemberName attribute, calls to the NotifyPropertyChanged method don't have to specify the property name as a string argument
{
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(name));
}
}
}
RelayCommand
namespace SectionGuardWPF.Core
{
class RelayCommand : ICommand
{
private Action<object> _execute;
private Func<object, bool> _canExecute;
public event EventHandler CanExecuteChanged
{
add { CommandManager.RequerySuggested += value; }
remove { CommandManager.RequerySuggested -= value; }
}
public RelayCommand(Action<object> execute, Func<object,bool> canExecute=null)
{
_execute = execute;
_canExecute = canExecute;
}
public bool CanExecute(object parameter)
{
return _canExecute == null || _canExecute(parameter);
}
public void Execute(object parameter)
{
_execute(parameter);
}
}
}
View Model
namespace SectionGuardWPF.MVVM.ViewModel
{
public class IProfilesViewModel:ObservableObject
{
#region Private Fields
private readonly string _connectionString = //Hidden
private ObservableCollection<IProfileModel> _iProfiles;
private ICommand _getIProfilesCommand;
private ICommand _addNewIProfileCommand;
private IProfileModel _iProfile = new IProfileModel();
#endregion
#region Constructor
public IProfilesViewModel()
{
// Set default Profile Database for the DataGrid upon View instantiation
IProfiles = GetIProfiles();
}
#endregion
#region Public Properties and Commands
/// <summary>
/// Public properties of the IProfilesViewModel Class (used for view binding with IProfilesSubView)
/// </summary>
public ObservableCollection<IProfileModel> IProfiles
{
get { return _iProfiles; }
set
{
_iProfiles = value;
OnPropertyChanged();
}
}
public IProfileModel IProfile
{
get { return _iProfile; }
set
{
_iProfile = value;
OnPropertyChanged();
}
}
public ICommand GetIProfilesCommand
{
get
{
if (_getIProfilesCommand == null)
{
_getIProfilesCommand = new RelayCommand(
param => GetIProfiles()
);
}
return _getIProfilesCommand;
}
}
public ICommand AddNewIProfileCommand
{
get
{
if (_addNewIProfileCommand == null)
{
_addNewIProfileCommand = new RelayCommand(
param => AddNewIProfile()
);
}
return _addNewIProfileCommand;
}
}
#endregion
#region Private Methods
private ObservableCollection<IProfileModel> GetIProfiles()
{
TableDataProvider tableDataProvider = new TableDataProvider(_connectionString);
tableDataProvider.QueryString = "SELECT * FROM [I Shape]";
IEnumerable<IProfileModel> iProfiles = tableDataProvider.Query<IProfileModel>();
ObservableCollection<IProfileModel> iProfileObsvCol = new ObservableCollection<IProfileModel>(iProfiles);
return iProfileObsvCol;
}
private void AddNewIProfile()
{
IProfiles.Add(
new IProfileModel
{
RECNO = IProfile.RECNO,
Name = IProfile.Name,
StaadName = IProfile.StaadName,
AX = IProfile.AX,
D = IProfile.D,
Bf = IProfile.Bf,
Tf = IProfile.Tf,
Tw = IProfile.Tw,
Ix = IProfile.Ix,
Iy = IProfile.Iy,
Iz = IProfile.Iz,
Ct = IProfile.Ct,
Zx = IProfile.Zx,
Zy = IProfile.Zy
}
);
}
#endregion
}
}
View
<UserControl x:Class="SectionGuardWPF.MVVM.View.IProfilesSubView"
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:SectionGuardWPF.MVVM.View"
xmlns:viewModel= "clr-namespace:SectionGuardWPF.MVVM.ViewModel"
xmlns:view="clr-namespace:SectionGuardWPF.MVVM.View"
mc:Ignorable="d"
d:DesignHeight="580" d:DesignWidth="1300">
<UserControl.DataContext>
<viewModel:IProfilesViewModel/>
</UserControl.DataContext>
<Grid>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="620"/>
<ColumnDefinition/>
</Grid.ColumnDefinitions>
<DataGrid x:Name="ProfilesDataGrid"
x:FieldModifier="public"
ItemsSource="{Binding IProfiles, Mode=TwoWay}">
</DataGrid>
<Border Grid.Column="1"
CornerRadius="20"
Background ="White"
Margin="10">
<Grid Margin="10">
<Grid.RowDefinitions>
<RowDefinition Height="50"/>
<RowDefinition/>
<RowDefinition Height="150"/>
</Grid.RowDefinitions>
<TextBlock Text="I-Profiles Data Viewer"
VerticalAlignment="Center"
HorizontalAlignment="Left"
Margin="20,0,0,0"
Foreground="Black"
FontSize="22"/>
<Grid Grid.Row="1">
<Grid.ColumnDefinitions>
<ColumnDefinition/>
<ColumnDefinition/>
</Grid.ColumnDefinitions>
<Grid.RowDefinitions>
<RowDefinition/>
<RowDefinition/>
<RowDefinition/>
<RowDefinition/>
<RowDefinition/>
<RowDefinition/>
<RowDefinition/>
</Grid.RowDefinitions>
<TextBlock Text="RECNO"
VerticalAlignment="Center"
HorizontalAlignment="Left"
Margin="20,0,0,0"
Foreground="#1A80FA"
Grid.Column="0"
Grid.Row="0"
FontSize="14"/>
<TextBox x:Name="RECNOTextBox"
Margin="0,0,20,0"
VerticalAlignment="Center"
HorizontalAlignment="Right"
Style="{StaticResource ParameterTextbox}"
Grid.Column="0"
Grid.Row="0"
Text="{Binding IProfile.RECNO, UpdateSourceTrigger=PropertyChanged, Mode=TwoWay}"/>
<TextBlock Text="Name"
VerticalAlignment="Center"
HorizontalAlignment="Left"
Margin="20,0,0,0"
Foreground="#1A80FA"
Grid.Column="0"
Grid.Row="1"
FontSize="14"/>
<TextBox x:Name="NameTextBox"
Margin="0,0,20,0"
VerticalAlignment="Center"
HorizontalAlignment="Right"
Style="{StaticResource ParameterTextbox}"
Grid.Column="0"
Grid.Row="1"
Text="{Binding IProfile.Name, UpdateSourceTrigger=PropertyChanged, Mode=TwoWay}"/>
<TextBlock Text="StaadName"
VerticalAlignment="Center"
HorizontalAlignment="Left"
Margin="20,0,0,0"
Foreground="#1A80FA"
Grid.Column="0"
Grid.Row="2"
FontSize="14"/>
<TextBox x:Name="StaadNameTextBox"
Margin="0,0,20,0"
VerticalAlignment="Center"
HorizontalAlignment="Right"
Style="{StaticResource ParameterTextbox}"
Grid.Column="0"
Grid.Row="2"
Text="{Binding IProfile.StaadName, UpdateSourceTrigger=PropertyChanged, Mode=TwoWay}"/>
<TextBlock Text="AX"
VerticalAlignment="Center"
HorizontalAlignment="Left"
Margin="20,0,0,0"
Foreground="#1A80FA"
Grid.Column="0"
Grid.Row="3"
FontSize="18"/>
<TextBox x:Name="AXTextBox"
Margin="0,0,20,0"
VerticalAlignment="Center"
HorizontalAlignment="Right"
Style="{StaticResource ParameterTextbox}"
Grid.Column="0"
Grid.Row="3"
Text="{Binding IProfile.AX, UpdateSourceTrigger=PropertyChanged, Mode=TwoWay}"/>
<TextBlock Text="D"
VerticalAlignment="Center"
HorizontalAlignment="Left"
Margin="20,0,0,0"
Foreground="#1A80FA"
Grid.Column="0"
Grid.Row="4"
FontSize="18"/>
<TextBox x:Name="DTextBox"
Margin="0,0,20,0"
VerticalAlignment="Center"
HorizontalAlignment="Right"
Style="{StaticResource ParameterTextbox}"
Grid.Column="0"
Grid.Row="4"
Text="{Binding IProfile.D, UpdateSourceTrigger=PropertyChanged, Mode=TwoWay}"/>
<TextBlock Text="Bf"
VerticalAlignment="Center"
HorizontalAlignment="Left"
Margin="20,0,0,0"
Foreground="#1A80FA"
Grid.Column="0"
Grid.Row="5"
FontSize="18"/>
<TextBox x:Name="BfTextBox"
Margin="0,0,20,0"
VerticalAlignment="Center"
HorizontalAlignment="Right"
Style="{StaticResource ParameterTextbox}"
Grid.Column="0"
Grid.Row="5"
Text="{Binding IProfile.Bf, UpdateSourceTrigger=PropertyChanged, Mode=TwoWay}"/>
<TextBlock Text="Tf"
VerticalAlignment="Center"
HorizontalAlignment="Left"
Margin="20,0,0,0"
Foreground="#1A80FA"
Grid.Column="0"
Grid.Row="6"
FontSize="18"/>
<TextBox x:Name="TfTextBox"
Margin="0,0,20,0"
VerticalAlignment="Center"
HorizontalAlignment="Right"
Style="{StaticResource ParameterTextbox}"
Grid.Column="0"
Grid.Row="6"
Text="{Binding IProfile.Tf, UpdateSourceTrigger=PropertyChanged, Mode=TwoWay}"/>
<TextBlock Text="Tw"
VerticalAlignment="Center"
HorizontalAlignment="Left"
Margin="20,0,0,0"
Foreground="#1A80FA"
Grid.Column="1"
Grid.Row="0"
FontSize="18"/>
<TextBox x:Name="TwTextBox"
Margin="0,0,20,0"
VerticalAlignment="Center"
HorizontalAlignment="Right"
Style="{StaticResource ParameterTextbox}"
Grid.Column="1"
Grid.Row="0"
Text="{Binding IProfile.Tw, UpdateSourceTrigger=PropertyChanged, Mode=TwoWay}"/>
<TextBlock Text="Ix"
VerticalAlignment="Center"
HorizontalAlignment="Left"
Margin="20,0,0,0"
Foreground="#1A80FA"
Grid.Column="1"
Grid.Row="1"
FontSize="18"/>
<TextBox x:Name="IxTextBox"
Margin="0,0,20,0"
VerticalAlignment="Center"
HorizontalAlignment="Right"
Style="{StaticResource ParameterTextbox}"
Grid.Column="1"
Grid.Row="1"
Text="{Binding IProfile.Ix, UpdateSourceTrigger=PropertyChanged, Mode=TwoWay}"/>
<TextBlock Text="Iy"
VerticalAlignment="Center"
HorizontalAlignment="Left"
Margin="20,0,0,0"
Foreground="#1A80FA"
Grid.Column="1"
Grid.Row="2"
FontSize="18"/>
<TextBox x:Name="IyTextBox"
Margin="0,0,20,0"
VerticalAlignment="Center"
HorizontalAlignment="Right"
Style="{StaticResource ParameterTextbox}"
Grid.Column="1"
Grid.Row="2"
Text="{Binding IProfile.Iy, UpdateSourceTrigger=PropertyChanged, Mode=TwoWay}"/>
<TextBlock Text="Iz"
VerticalAlignment="Center"
HorizontalAlignment="Left"
Margin="20,0,0,0"
Foreground="#1A80FA"
Grid.Column="1"
Grid.Row="3"
FontSize="18"/>
<TextBox x:Name="IzTextBox"
Margin="0,0,20,0"
VerticalAlignment="Center"
HorizontalAlignment="Right"
Style="{StaticResource ParameterTextbox}"
Grid.Column="1"
Grid.Row="3"
Text="{Binding IProfile.Iz, UpdateSourceTrigger=PropertyChanged, Mode=TwoWay}"/>
<TextBlock Text="Ct"
VerticalAlignment="Center"
HorizontalAlignment="Left"
Margin="20,0,0,0"
Foreground="#1A80FA"
Grid.Column="1"
Grid.Row="4"
FontSize="18"/>
<TextBox x:Name="CtTextBox"
Margin="0,0,20,0"
VerticalAlignment="Center"
HorizontalAlignment="Right"
Style="{StaticResource ParameterTextbox}"
Grid.Column="1"
Grid.Row="4"
Text="{Binding IProfile.Ct, UpdateSourceTrigger=PropertyChanged, Mode=TwoWay}"/>
<TextBlock Text="Zx"
VerticalAlignment="Center"
HorizontalAlignment="Left"
Margin="20,0,0,0"
Foreground="#1A80FA"
Grid.Column="1"
Grid.Row="5"
FontSize="18"/>
<TextBox x:Name="ZxTextBox"
Margin="0,0,20,0"
VerticalAlignment="Center"
HorizontalAlignment="Right"
Style="{StaticResource ParameterTextbox}"
Grid.Column="1"
Grid.Row="5"
Text="{Binding IProfile.Zx, UpdateSourceTrigger=PropertyChanged, Mode=TwoWay}"/>
<TextBlock Text="Zy"
VerticalAlignment="Center"
HorizontalAlignment="Left"
Margin="20,0,0,0"
Foreground="#1A80FA"
Grid.Column="1"
Grid.Row="6"
FontSize="18"/>
<TextBox x:Name="ZyTextBox"
Margin="0,0,20,0"
VerticalAlignment="Center"
HorizontalAlignment="Right"
Style="{StaticResource ParameterTextbox}"
Grid.Column="1"
Grid.Row="6"
Text="{Binding IProfile.Zy, UpdateSourceTrigger=PropertyChanged, Mode=TwoWay}"/>
</Grid>
<StackPanel Grid.Row="2"
Orientation="Horizontal">
<Button x:Name="AddButton"
Style="{StaticResource AddButton}"
Content="Add"
Background="#28C941"
Height="50"
Width="150"
Margin="85,0,0,0"
Command="{Binding AddNewIProfileCommand}"/>
<Button x:Name="EditButton"
Style="{StaticResource AddButton}"
Content="Edit"
Background="#FFBD2E"
Height="50"
Width="150"
Margin="20,0,0,0"/>
<Button x:Name="DeleteButton"
Style="{StaticResource AddButton}"
Content="Delete"
Background="#FF6059"
Height="50"
Width="150"
Margin="20,0,0,0"/>
</StackPanel>
</Grid>
</Border>
</Grid>
</UserControl>
My Model class is a class called the IProfileModel that represents the I-Shape Profiles, I have made so that it inherits from the ObservableObject class so that it can use the NotifyPropertyChanged methods and I have made so that the properties of the Model class has implemented the OnPropertyChanged() Method.
In my View, I have bound the source of the DataGrid to the IProfiles which is an ObservableCollection that stores instances of the IProfileModel. Each TextBox corresponds to one property of the IProfileModel class, thus the Text property of each TextBox is bound to its respective nested property of the IProfile property of the ViewModel. The "Add" Button is bound to the respective ICommand in the ViewModel called the AddNewIProfileCommand
In my ViewModel, I have added the IProfileModel as one of its properties using the name IProfile, the TextBox.Text properties are bound to the nested properties of the IProfile as shown in the XAML of the View. As for the AddNewIProfileCommand, I have made so that it corresponds to a private method called the AddNewIProfile() which will add a new IProfileModel object whose properties will refer to the nested properties of the IProfile property that is bound to the TextBoxes.
Edit:
I want to add that the AddNewIProfile() will add the new IProfileModel object to the IProfiles which is bound to the DataGrid
My main issue is that whenever I modified the TextBoxes and then clicked on the Button to add the profiles to the DataGrid, the newly added entry to the DataGrid is always a IProfileModel with empty property values (all string properties of the IProfileModel are null and all numerical type properties are 0). It seems like modifying the TextBoxes does not change the nested properties of the IProfile even though I have set the UpdateSourceTrigger to PropertyChanged and the Mode to Two Way and the IProfile itself is of the IProfileModel class which has inherited from the ObservableObject class.
Lastly, I know that my question is quite similar to this one but I have followed the suggestions there and tried to match their solution but I somehow can't get it to work.
Thanks!
Edit:
Added some before - after picture of the DataGrid after the "Add" Button is pressed:
Edit:
The ParameterTextbox Style which was the cause of the error as pointed out by Cédric Moers in the comments:
<Style TargetType="{x:Type TextBox}"
x:Key="ParameterTextbox">
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="{x:Type TextBox}">
<Border CornerRadius="5"
Background="White"
Width="180"
Height="35"
BorderThickness="3"
BorderBrush="#EAEAEA">
<Grid>
<Rectangle StrokeThickness="1"/>
<TextBox Margin="1"
Text="{TemplateBinding Text}"
BorderThickness="0"
Background="Transparent"
VerticalContentAlignment="Center"
Padding="5"
Foreground="Black"
x:Name="SearchBox"/>
</Grid>
</Border>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
I tried to replicate your problem but I had to remove the styles since you did not provide them. It works at my side, so perhaps the problem lies within the style?
Please delete your styles for the textboxes (ParameterTextbox) and see if it works then. If you can provide me with the source code for the style, I can take a look at it. Maybe you are overriding the text property.
edit after it turned out the style was the issue
here is an example of the style you want to accomplish in a minimalistic way.
<UserControl.Resources>
<ControlTemplate x:Key="RoundedTextBoxCt">
<Border
Width="{TemplateBinding Width}"
Height="{TemplateBinding Height}"
BorderBrush="{TemplateBinding BorderBrush}"
BorderThickness="{TemplateBinding BorderThickness}"
Background="{TemplateBinding Background}"
x:Name="Bd"
CornerRadius="5">
<ScrollViewer
Padding="{TemplateBinding Padding}"
VerticalContentAlignment="{TemplateBinding VerticalContentAlignment}"
Foreground="{TemplateBinding Foreground}"
x:Name="PART_ContentHost"/>
</Border>
</ControlTemplate>
<Style x:Key="ParameterTextBox" TargetType="TextBox">
<Setter Property="Width" Value="180"/>
<Setter Property="Height" Value="35"/>
<Setter Property="VerticalContentAlignment" Value="Center"/>
<Setter Property="Padding" Value="5"/>
<Setter Property="Foreground" Value="Black"/>
<Setter Property="BorderBrush" Value="#EAEAEA"/>
<Setter Property="BorderThickness" Value="3"/>
<Setter Property="Background" Value="White"/>
<Setter Property="Template" Value="{StaticResource RoundedTextBoxCt}"/>
</Style>
...
</UserControl.Resources>
I made the control template as a separate resource, this way 'rounded textbox' can be put inside of some 'shared' assembly, and you will be able to use it for other projects as well.
It is minimalistic, as in the minimal you'll need. If you want a full-fledged text box, copy the style from here and modify it: https://learn.microsoft.com/en-us/dotnet/desktop/wpf/controls/textbox-styles-and-templates?view=netframeworkdesktop-4.8
it might look scary, but most of the time it comes down to modifying only a few rules. Once you get the hang of it, it's quite easy.
Instead of working with the setters, and even a separate control template resource, you could hard-code everything within the control template, WITHIN the setter of the control template of the textbox style, but that's up to you.
Good luck!

LongListSelector Data Binding Issue

I am a beginner in windows Windows phone programming.
i am trying to implement LongListSelector to display group by products.
here are my classes :
public class ProductMaster {
public string Name { get; set; }
public List<ProductSubMaster> Models { get; set; }
}
public class ProductSubMaster
{
public string Name { get; set; }
public ProductSubMasterProperty modelProperty { get; set; }
}
public class ProductSubMasterProperty{
public string ProNo { get; set; }
public Uri ProImage { get; set; }
}
and my xaml :
<phone:LongListSelector
x:Name="ProductList"
ItemsSource="{Binding objProduct}"
Background="Transparent"
LayoutMode="List"
IsGroupingEnabled="True"
HideEmptyGroups ="False">
<phone:LongListSelector.GroupHeaderTemplate>
<DataTemplate>
<Border Background="Transparent" Padding="5">
<Border Background="Black" BorderBrush="Black" BorderThickness="2" Width="500"
Height="62" Margin="0,0,18,0" HorizontalAlignment="Left">
<TextBlock Text="{Binding Path=[0].Name}" Foreground="White" FontSize="25" Padding="10"
FontFamily="{StaticResource PhoneFontFamilySemiLight}" HorizontalAlignment="Center" VerticalAlignment="Center"/>
</Border>
</Border>
</DataTemplate>
</phone:LongListSelector.GroupHeaderTemplate>
<phone:LongListSelector.ItemTemplate>
<DataTemplate>
<StackPanel Orientation="Horizontal">
<Image x:Name="searchimg" HorizontalAlignment="Left" VerticalAlignment="Center" Margin="10,0,0,0" Source="{Binding Path=Models.modelProperty.ProImage}" Height="100" Width="100" ></Image>
<TextBlock x:Name="ProductName" Margin="20,0,0,0" HorizontalAlignment="Center" VerticalAlignment="Center" Width="250" TextWrapping="Wrap" Foreground="Black" Text="{Binding Path=Models.Name}" FontSize="30"></TextBlock>
<Image x:Name="bookmarkimg" HorizontalAlignment="Right" Margin="0,0,0,0" VerticalAlignment="Center" Source="/Assets/Media/star.png" Height="40" Width="30" Stretch="Uniform" ></Image>
</StackPanel>
</DataTemplate>
</phone:LongListSelector.ItemTemplate>
</phone:LongListSelector>
i am facing the issue for binding ItemTemplate
Please help me out
Thank you.
i have added listbox in itemtemplate solved my issue
here is my updated code
<phone:LongListSelector.ItemTemplate>
<DataTemplate>
<ListBox x:Name="LstFeaturesData" Visibility="Visible" ItemsSource="{Binding Path=Models}" Margin="0,0">
<ListBox.ItemTemplate>
<DataTemplate>
<StackPanel Orientation="Horizontal">
<Image x:Name="searchimg" HorizontalAlignment="Left" VerticalAlignment="Center" Margin="10,0,0,0" Source="{Binding Path=modelProperty.ProImage}" Height="100" Width="100" ></Image>
<TextBlock x:Name="ProductName" Margin="20,0,0,0" HorizontalAlignment="Center" VerticalAlignment="Center" Width="250" TextWrapping="Wrap" Foreground="Black" Text="{Binding Path=Name}" FontSize="30"></TextBlock>
<Image x:Name="bookmarkimg" HorizontalAlignment="Right" Margin="0,0,0,0" VerticalAlignment="Center" Source="/Assets/Media/star.png" Height="40" Width="30" Stretch="Uniform" ></Image>
</StackPanel>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
</DataTemplate>
</phone:LongListSelector.ItemTemplate>

windows phone 8.1: Hide stackpanel if textblock is empty

my xaml code is given below
my whole xaml
<Page
x:Class="App13.MainPage"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="using:App13"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
mc:Ignorable="d"
xmlns:converter="using:App13"
Background="{ThemeResource ApplicationPageBackgroundThemeBrush}">
<Page.Resources>
<converter:BooleanToVisibilityConvertor x:Key="visibilityConverter"/>
</Page.Resources>
<Grid Margin="0,30.333,0,-0.333" Background="Black" >
<!--<Button Margin="0,-105,0,563" ScrollViewer.VerticalScrollBarVisibility="Visible" ScrollViewer.VerticalScrollMode="Enabled" x:Name="one" Content="Getdata" RenderTransformOrigin="0.367,-0.585" Height="92" Width="112" Click="Button_Click"/>-->
<ListView IsItemClickEnabled="True" IsEnabled="True" ItemClick="listview1_ItemClick" ScrollViewer.VerticalScrollMode="Enabled" ScrollViewer.VerticalScrollBarVisibility="Visible" x:Name="listview1" ItemsSource="{Binding Taxi}" FontSize="17" Margin="10,0,-10,0">
<ListView.Items>
<StackPanel Background="Blue">
<TextBlock Text="eqweqwe" Foreground="AntiqueWhite"></TextBlock>
<TextBlock Foreground="Aqua" Text="sadwdasdasdasd"></TextBlock>
</StackPanel>
</ListView.Items>
<ListView.ItemTemplate>
<DataTemplate>
<Grid>
<Border Tapped="Border_Tap" Height="90">
<StackPanel x:Name="ParentStackPanel" Width="380" Margin="0,5,0,5">
<StackPanel Margin="0,-80,0,0" Background="Black" Grid.Column="0" Grid.Row="0" VerticalAlignment="Center" HorizontalAlignment="Left">
<Image Width="48"
Height="48"
Source="{Binding Icon}"
/>
</StackPanel>
<StackPanel Name="expand" Background="White" Height="220" >
<StackPanel Orientation="Horizontal" Margin="10,10,0,0" Visibility="{Binding Invoice.Minimum_Fare, Converter={StaticResource visibilityConverter}}">
<TextBlock AllowDrop="True" Grid.Column="1" Margin="50,0,0,0" HorizontalAlignment="Left" FontSize="10" Foreground="Black" Text="Approx Travel Time" ></TextBlock>
<TextBlock Name="tb" Grid.Column="2" HorizontalAlignment="Right" AllowDrop="True" FontSize="6" Foreground="Black" Width="204" Text="{Binding Invoice.Minimum_Fare}" >
</TextBlock>
</StackPanel>
<StackPanel Orientation="Horizontal" Margin="10,3,0,0" >
<TextBlock Width="183" Margin="50,0,0,0" FontSize="16" Foreground="Black" Text="Minimum Fare"></TextBlock>
<TextBlock FontSize="16" Foreground="Black" Text="{Binding Invoice.Minimum_Fare}" Width="131">
</TextBlock>
</StackPanel>
<StackPanel Margin="0,5,0,5" Height="5" Grid.Row="1" Background="Aqua" x:Name="something">
</StackPanel>
</StackPanel>
</Border>
</Grid>
</DataTemplate>
</ListView.ItemTemplate>
</ListView>
</Grid>
</Page>
using visualstatemanager or some front end techniques i want to hide stackpanel if the textblock text is empty
I modal is this
public class Example {
public string CompanyName { get; set;}
public string Invoice { get; set; }
public string Lat { get; set; }
public string Lng { get; set; }
}
by i dont know how to bind visibility with stack panel
You can write converter to hide/show stackpanel
public class BooleanToVisibilityConvertor: IValueConverter
{
public object Convert(object value, Type targetType, object parameter, string language)
{
if(value!=null)
{
if (!string.IsNullOrEmpty(value.ToString()))
{
return Visibility.Visible;
}
}
return Visibility.Collapsed;
}
public object ConvertBack(object value, Type targetType, object parameter, string language)
{
throw new NotImplementedException();
}
}
In xaml add converter
<Page
x:Class="App1.MainPage"
xmlns:converter="using:App1">
<Page.Resources>
<converter:BooleanToVisibilityConvertor x:Key="visibilityConverter"/>
</Page.Resources>
<StackPanel Background="Aqua" Height="200" Orientation="Horizontal" Margin="10,3,0,0" Visibility="{Binding Invoice, Converter={StaticResource visibilityConverter}}">
<TextBlock FontSize="16" Text="{Binding Invoice}" Name="tb" Height="300" Width="300" Foreground="Black" >
</TextBlock>
</StackPanel>
I have hardcoded text value for testing. You can use binding.
Check and let me know if any issue.
You cannot do this with visual states in Windows Phone 8. I suggest you create a simple StringToVisibilityConverter (returning Visibility.Collapsed on empty string) and use it to bind your StackPanel visibility.
<StackPanel Visibility="{Binding Path=stcVisiblity}" >
<TextBlock FontSize="16" Foreground="Black" Text="{Binding Invoice}">
</TextBlock>
</StackPanel>
and the class
public class Example {
public string CompanyName { get; set;}
public string Invoice { get; set; }
public string Lat { get; set; }
public string stcVisiblity { get; set; }
public string Lng { get; set; }
}
and than code
something like this to code,
than you can bind this value as per your need :
stcVisiblity = "Visible"; or
stcVisiblity = "Collapsed";

Values from database not showing up on xaml page after using groupby statement

I have a dto,method and xaml file below. The method returns duplicates which is fine. I only want to display one on my xaml page. I used a groupby and I was able
to display one item but the values for RouteNbr and Day are not displayed on the xaml page.
Do you know what am doing wrong?
public class CSDto
{
public Int32 ID { get; set; }
public Int32 RouteNbr { get; set; }
public Int32 Day { get; set; }
public String Month { get; set; }
public String Year { get; set; }
}
private void GetAllCsrActPlansByCsrId(Int32 CssId)
{
try
{
string getCs = Convert.ToString(CssId);
var getRouteInfoProfile = MySol.GetByCustomerNbr(getCs);
var queryResult = getRouteInfoProfile;
grdVwRouteAct.DataContext = queryResult.GroupBy(g=>g.RouteNbr).Distinct();
}
catch (Exception ex)
{
customutility.ApplicationErrorlog(UserID, ex.Message, DateTime.Now.ToString());
}
}
<GridView.ItemTemplate>
<DataTemplate>
<Button Style="{StaticResource CSRProfile}" Margin="0" Padding="0" Height="Auto" Width="Auto" Background="MediumAquamarine">
<StackPanel Tag="cpActionPlanBlock" Width="275" Height="90" HorizontalAlignment="Left" VerticalAlignment="Center" Orientation="Horizontal" Margin="0">
<Image Source="/Assets/Images/CSRProfile-checkicon.gif" Width="49" Height="65" VerticalAlignment="Center" Margin="10"/>
<StackPanel Orientation="Vertical" VerticalAlignment="Center" Margin="10,0">
<StackPanel Orientation="Horizontal">
<TextBlock Tag="cpRouteNumber" Style="{ThemeResource BasicFontStyle4B}" Text="{Binding RouteNbr}" VerticalAlignment="Top" Margin="0,0,0,5"/>
<TextBlock Style="{ThemeResource BasicFontStyle4B}" Text="-" VerticalAlignment="Top" Margin="5,0,5,0"/>
<TextBlock Tag="cpDay" x:Uid="queueItemType" Style="{ThemeResource BasicFontStyle4B}" Text="{Binding Day}" VerticalAlignment="Top" Margin="0,0,0,5"/>
</StackPanel>
<StackPanel Orientation="Horizontal">
<TextBlock Tag="cpNumberofActions" Style="{ThemeResource BasicFontStyle4B}" Text="[Y]" VerticalAlignment="Top" Margin="0,0,5,0"/>
<TextBlock Tag="cpLblActions" Style="{ThemeResource BasicFontStyle4B}" Text="Actions" x:Uid="cpActions" VerticalAlignment="Top" Margin="0,0,15,5"/>
</StackPanel>
</StackPanel>
</StackPanel>
</Button>
</DataTemplate>
</GridView.ItemTemplate>

Selecting multiple entries from XML with same name WP7

I have tried for several hours and searching on the net for examples on how to pull multiple elements with the same name however different attributes and binding those to my XAML in my app for wp7,
the easiest way for me to explain is to simply show you,
heres what I have so far
public class Match
{
public string HomeTeam { get; set; }
public string AwayTeam { get; set; }
public string HomeScore { get; set; }
public string AwayScore { get; set; }
public string GoalsPlayer { get; set; }
public string goal { get; set; }
public string GoalsTime { get; set; }
public string DismissalsPlayer { get; set; }
public string DismissalsTime { get; set; }
public string BookingPlayer { get; set; }
public string BookingTime { get; set; }
public string GameTime { get; set; }
}
void wc_DownloadStringCompleted(object sender, DownloadStringCompletedEventArgs e)
{
XElement element = XElement.Parse(e.Result);
try
{
listBox2.ItemsSource = from item in element.Descendants("competition")
from match in item.Elements("match").Where(arg => arg.Attribute("awayTeam").Value == team | arg.Attribute("homeTeam").Value == team)
select new Match
{
HomeTeam = (string)match.Attribute("homeTeam"),
AwayTeam = (string)match.Attribute("awayTeam"),
HomeScore = (string)match.Attribute("homeTeamScore"),
AwayScore = (string)match.Attribute("awayTeamScore"),
GoalsPlayer = (string)match.Attribute("playerName"),
GoalsTime = (string)match.Attribute("time"),
};
}
catch (Exception ex)
{
Debug.WriteLine(ex.StackTrace);
}
here is my XAML
<ListBox Name="listBox2" Grid.Row="0">
<ListBox.ItemTemplate>
<DataTemplate>
<StackPanel Name="teams" Orientation="Vertical">
<StackPanel Orientation="Horizontal">
<TextBlock Margin="0,10,0,0" Foreground="White" HorizontalAlignment="Left" Text="{Binding HomeTeam}"/>
<TextBlock Margin="10,10,30,0" Foreground="White" Text="{Binding HomeScore}" TextWrapping="Wrap" FontSize="20" />
<TextBlock Margin="0,10,0,0" Foreground="White" HorizontalAlignment="Left" Text="{Binding AwayTeam}"/>
<TextBlock Margin="10,10,30,0" Foreground="White" Text="{Binding AwayScore}" TextWrapping="Wrap" FontSize="20" />
</StackPanel>
<StackPanel Name="scores" Orientation="Horizontal">
<TextBlock Margin="0,10,0,0" Foreground="White" Text="{Binding GoalsPlayer}" TextWrapping="Wrap" FontSize="20" />
<TextBlock Margin="10,10,30,0" Foreground="White" Text="{Binding GoalsTime}" TextWrapping="Wrap" FontSize="20" />
</StackPanel>
<StackPanel Name="dismissals">
<TextBlock Foreground="White" Text="{Binding DismissalsPlayer}" TextWrapping="Wrap" FontSize="20"/>
<TextBlock Foreground="White" Text="{Binding DismissalsTime}" TextWrapping="Wrap" FontSize="20"/>
</StackPanel>
</StackPanel>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
here is my XML
<match homeTeam="Arsenal" awayTeam="Liverpool" homeTeamScore="0" awayTeamScore="2">
<goal time="77:13" playerName="Aaron Ramsey" />
<goal time="89:57" playerName="Luis Suarez"/>
<dismissal time="69:59" playerName="Emmanuel Frimpong"/>
</match>
I understand that I will only get one entry on my Page for Goals, which would be the first goal element in my XML
how can I go about that and implement every
<goal ...>
<goal ...>
into my Datatemplate that currently only shows the first entry, another potential problem is I cannot guarantee how many goals there will be so I am a really unsure on how to go about it entirely
thanks
John
Should playerName even resolve on your match? Because that's where you are resolving it in your XML query.
Regardless, what you are looking for here is a sub-object that can be held in a list property of the Match object:
listBox2.ItemsSource = from item in element.Descendants("competition")
from match in item.Elements("match")
.Where(arg => arg.Attribute("awayTeam").Value == team ||
arg.Attribute("homeTeam").Value == team)
select new Match
{
HomeTeam = (string)match.Attribute("homeTeam"),
AwayTeam = (string)match.Attribute("awayTeam"),
HomeScore = (string)match.Attribute("homeTeamScore"),
AwayScore = (string)match.Attribute("awayTeamScore"),
Goals = match.Elements("goals").Select(ev => new MatchEvent
{
Player = (string)ev.Attribute("playerName"),
Time = (string)ev.Attribute("time")
}).ToList(),
Dismissals = match.Elements("dismissals").Select(ev => new MatchEvent
{
Player = (string)ev.Attribute("playerName"),
Time = (string)ev.Attribute("time")
}).ToList(),
};
And the updated XAML:
<ListBox Name="listBox2" Grid.Row="0">
<ListBox.ItemTemplate>
<DataTemplate>
<StackPanel Name="teams" Orientation="Vertical">
<StackPanel Orientation="Horizontal">
<TextBlock Margin="0,10,0,0" Foreground="White" HorizontalAlignment="Left" Text="{Binding HomeTeam}"/>
<TextBlock Margin="10,10,30,0" Foreground="White" Text="{Binding HomeScore}" TextWrapping="Wrap" FontSize="20" />
<TextBlock Margin="0,10,0,0" Foreground="White" HorizontalAlignment="Left" Text="{Binding AwayTeam}"/>
<TextBlock Margin="10,10,30,0" Foreground="White" Text="{Binding AwayScore}" TextWrapping="Wrap" FontSize="20" />
</StackPanel>
<ItemsControl ItemsSource="{Binding Goals}">
<ItemsControl.ItemTemplate>
<DataTemplate>
<StackPanel Name="scores" Orientation="Horizontal">
<TextBlock Margin="0,10,0,0" Foreground="White" Text="{Binding Player}" TextWrapping="Wrap" FontSize="20" />
<TextBlock Margin="10,10,30,0" Foreground="White" Text="{Binding Time}" TextWrapping="Wrap" FontSize="20" />
</StackPanel>
</DataTemplate>
</ItemsControl.ItemTemplate>
</ItemsControl>
<ItemsControl ItemsSource="{Binding Dismissals}">
<ItemsControl.ItemTemplate>
<DataTemplate>
<StackPanel Name="scores" Orientation="Horizontal">
<TextBlock Margin="0,10,0,0" Foreground="White" Text="{Binding Player}" TextWrapping="Wrap" FontSize="20" />
<TextBlock Margin="10,10,30,0" Foreground="White" Text="{Binding Time}" TextWrapping="Wrap" FontSize="20" />
</StackPanel>
</DataTemplate>
</ItemsControl.ItemTemplate>
</ItemsControl>
</StackPanel>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>

Categories