WPF Dynamic add ListViewItem with detals - c#

I want to add ListViewItem with changed details like image's link, text in textbox etc. How can I do it?
<ListView VerticalAlignment="Bottom" Margin="10" Height="170" Foreground="LightSteelBlue">
<ListViewItem>
<StackPanel Orientation="Horizontal">
<TextBlock Text="01" VerticalAlignment="Center"/>
<Ellipse Margin="20,0" Width="30" Height="30" VerticalAlignment="Center">
<Ellipse.Fill>
<ImageBrush ImageSource="images/pobrane.jpg"/>
</Ellipse.Fill>
</Ellipse>
<TextBlock Text="Three Days Grace - I Hate Everything About You (Official Music Video)" Width="115" TextTrimming="CharacterEllipsis" VerticalAlignment="Center" />
<TextBlock Text="3:45" Margin="10,0" VerticalAlignment="Center" />
</StackPanel>
</ListViewItem>
</ListView>
I want to make function which will add the same code like i showed you with changed details.

You can use the ItemTemplate and the ItemsSource properties of the WPF Listview and the Binding concepts.
Just for an example, starting from your question:
You can add the following code to the MainWindow files of a new WPF project:
The MainWindow.xaml file should look like this:
<Window x:Class="WpfApp1.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"
mc:Ignorable="d"
Title="MainWindow" Height="450" Width="800">
<Grid>
<Button Click="Button_Click"
VerticalAlignment="Top"
HorizontalAlignment="Left"
Margin="10"
Content="Add item"/>
<ListView VerticalAlignment="Bottom"
Margin="10"
Height="170"
ItemsSource="{Binding Tracks}"
Foreground="LightSteelBlue">
<ListView.ItemTemplate>
<DataTemplate>
<StackPanel Orientation="Horizontal">
<TextBlock Text="{Binding Number}"
VerticalAlignment="Center" />
<Ellipse Margin="20,0"
Width="30"
Height="30"
VerticalAlignment="Center">
<Ellipse.Fill>
<ImageBrush ImageSource="{Binding Image}" />
</Ellipse.Fill>
</Ellipse>
<TextBlock Text="{Binding Name}"
Width="115"
TextTrimming="CharacterEllipsis"
VerticalAlignment="Center" />
<TextBlock Text="{Binding Length}"
Margin="10,0"
VerticalAlignment="Center" />
</StackPanel>
</DataTemplate>
</ListView.ItemTemplate>
</ListView>
</Grid>
</Window>
And the MainWindow.xaml.cs file should look like this:
using System;
using System.Collections.ObjectModel;
using System.Windows;
using System.Windows.Media;
using System.Windows.Media.Imaging;
namespace WpfApp1
{
/// <summary>
/// Interaction logic for MainWindow.xaml
/// </summary>
public partial class MainWindow : Window
{
public ObservableCollection<Track> Tracks { get; set; }
public MainWindow()
{
InitializeComponent();
this.DataContext = this;
Tracks = new ObservableCollection<Track>();
AddTrack("01","Three Days Grace - I Hate Everything About You (Official Music Video)", "3:45", new BitmapImage(new Uri("pack://application:,,,/WpfApp1;component/Resources/pobrane.jpg")));
}
public void AddTrack (string number, string name, string length, ImageSource image)
{
var track = new Track();
track.Number = number;
track.Name = name;
track.Length = length;
track.Image = image;
Tracks.Add(track);
}
private void Button_Click(object sender, RoutedEventArgs e)
{
AddTrack("01", "Three Days Grace - I Hate Everything About You (Official Music Video)", "3:45", new BitmapImage(new Uri("pack://application:,,,/WpfApp1;component/Resources/pobrane.jpg")));
}
}
public class Track
{
public string Number { get; set; }
public string Name { get; set; }
public string Length { get; set; }
public ImageSource Image { get; set; }
}
}
Of course, this is just as a starting point. You should go on searching and reading the MVVM concepts and move the logic to a viewmodel.

Related

How can I use DelegateCommand correctly?

In the debug mode, goes from constructor to the set method, but in the get method does not enter at any point, which I think is the problem, but I don't know how to solved.
In the .xaml file I defined the button.
<dx:ThemedWindow
x:Class="ProductsModule.View.ProductView"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:dx="http://schemas.devexpress.com/winfx/2008/xaml/core"
Title="MenuView" Height="800" Width="1000">
<Grid Margin="20" VerticalAlignment="Top" Background="White" Height="420" DataContext="{Binding Detail}">
<Grid.Effect>
<DropShadowEffect BlurRadius="20" ShadowDepth="1"/>
</Grid.Effect>
<StackPanel Margin="750 70 70 70" HorizontalAlignment="Left">
<TextBlock Text="{Binding Name}" FontSize="18" Margin="0 5" Foreground="#FF6A6A6A"/>
<Button Command="{Binding ShowCommand }">Add data</Button>
</StackPanel>
</Grid>
</dx:ThemedWindow>
In .xaml.cs file I defined datacontext.
public SecondView()
{
InitializeComponent();
this.DataContext = new ViewModel();
}
VIEW MODEL
public ViewModel()
{
ShowCommand = new DelegateCommand(ShowMethod);
}
public ICommand ShowCommand
{
get;
set;
}
private void ShowMethod()
{
OrderView orderView = new OrderView();
orderView.Show();
}
When I press the button, ShowMethod() is not called and does not do anything.

Databinding to command inside of listview not working in UWP/MVVM-Light

I want to have a Delete button for every element in my ListView, I searched stackoverflow but none answer my question.
I tried giving my ListView a x:Name="QuizListView" and using ElementName inside the ListView to bind the command to the button.
QuizOverview.xaml
<Page
x:Name="QuizOverviewPage"
x:Class="UwpApp.View.QuizOverview"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="using:UwpApp.View"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
mc:Ignorable="d"
Background="{ThemeResource ApplicationPageBackgroundThemeBrush}"
DataContext="{Binding QuizOverviewInstance, Source={StaticResource Locator}}">
<StackPanel Margin="20">
<TextBlock Text="Quizzen" FontSize="48"/>
<ListView x:Name="QuizListView" ItemsSource="{Binding Quizzes}" Margin="0,20" SelectionMode="Single" SelectionChanged="QuizListView_SelectionChanged">
<ListView.ItemTemplate>
<DataTemplate>
<ListViewItem>
<StackPanel Orientation="Horizontal">
<Border CornerRadius="10" BorderBrush="Black" BorderThickness="2" Height="100" Width="400" VerticalAlignment="Center">
<TextBlock Text="{Binding Name}" VerticalAlignment="Center" HorizontalAlignment="Center" FontSize="36"></TextBlock>
</Border>
<Button VerticalAlignment="Center" Padding="20" Margin="20">Edit</Button>
<Button VerticalAlignment="Center" Padding="20" Margin="0" Command="{Binding Path=DataContext.DeleteQuizCommand, ElementName=QuizListView}" CommandParameter="{Binding}">Delete</Button>
</StackPanel>
</ListViewItem>
</DataTemplate>
</ListView.ItemTemplate>
</ListView>
<Button Padding="20" Command="{Binding CreateQuizCommand}">Add New Quiz</Button>
</StackPanel>
</Page>
QuizOverviewViewModel.cs
public class QuizOverviewViewModel : ViewModelBase
{
public string Title { get; set; }
public ObservableCollection<Quiz> Quizzes { get; set; }
public RelayCommand<Quiz> DeleteQuizCommand { get; set; }
public RelayCommand CreateQuizCommand { get; set; }
public QuizOverviewViewModel()
{
Title = "Quizzen";
Quizzes = new ObservableCollection<Quiz> { new Quiz(1, "Test Quiz 1"), new Quiz(2, "Test Quiz 2"), new Quiz(3, "Test Quiz 3") };
DeleteQuizCommand = new RelayCommand<Quiz>(DeleteQuiz);
CreateQuizCommand = new RelayCommand(CreateQuizTest);
}
public void DeleteQuiz(Quiz quiz)
{
Quizzes.Remove(Quizzes.Single(i => i.Id == quiz.Id));
}
public void CreateQuizTest()
{
Quizzes.Add(new Quiz(4, "Test Quiz Creation!"));
}
}
Quiz.cs
namespace UwpApp.Model
{
public class Quiz
{
public long Id { get; set; }
public string Name { get; set; }
public Quiz(long id, string name)
{
Id = id;
Name = name;
}
}
}
The Button does nothing with my current code, while the command does work outside of the ListView.
Databinding to command inside of listview not working in UWP/MVVM-Light
The problem is that you insert ListViewItem in to DataTemplate. It will cause that ListViewItem contains sub-ListViewItem in the Visual Tree and you could not access correct DataContext with element name in your button. Please remove ListViewItem from your code.
<DataTemplate>
<StackPanel Orientation="Horizontal">
<Border CornerRadius="10" BorderBrush="Black" BorderThickness="2" Height="100" Width="400" VerticalAlignment="Center">
<TextBlock Text="{Binding Name}" VerticalAlignment="Center" HorizontalAlignment="Center" FontSize="36"></TextBlock>
</Border>
<Button VerticalAlignment="Center" Padding="20" Margin="20">Edit</Button>
<Button VerticalAlignment="Center" Padding="20" Margin="0" Command="{Binding Path=DataContext.DeleteQuizCommand, ElementName=QuizListView}" CommandParameter="{Binding}">Delete</Button>
</StackPanel>
</DataTemplate>

Send listbox selected items to another listbox on a different uwp page

I have a list on page one with car objects. I want to click on a car from the list and click a button which will send the selected car to a list on another uwp page.
I am trying to put the listCar.selecteditems in an empty list I created called purchase and display purchase on page 2. With the code I have at the moment, it is only displaying ProjectName_Car in the list on page 2.
Any help on displaying this properly is appreciated.
Page1.xaml.cs
private void Add_Click(object sender, RoutedEventArgs e)
{
var query = listCars.SelectedItems.ToList().Cast<Car>();
foreach (var item in query)
{
purchase.Add(item);
}
liistCar.ItemsSource = purchase;
Frame.Navigate(typeof(Page2), listCar.Items);
}
Page2.xaml.cs
protected override void OnNavigatedTo(NavigationEventArgs e)
{
base.OnNavigatedTo(e);
lstCars.ItemsSource = e.Parameter as List<Car> ;
}
Edit: Page1.xaml
<ListBox Name="listCars" ItemsSource="{x:Bind cars}" >
<ListBox.ItemTemplate>
<DataTemplate x:DataType="Car">
<StackPanel Padding="20">
<Image Width="200" Height="150" HorizontalAlignment="Left" Source="{x:Bind imgCar}" />
<TextBlock FontSize="22" HorizontalAlignment="Left" Text="{x:Bind Name}" Style="{StaticResource HeaderTextBlockStyle}"/>
<TextBlock FontSize="16" HorizontalAlignment="Left"> € <Run Text="{Binding Price}" /></TextBlock>
</StackPanel>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
This one transfers your selected car list object to next page as parameter with all its properties.
MainPage.xaml
<Page
x:Class="App1.MainPage"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="using:App1"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
mc:Ignorable="d"
x:Name="YourPage"
Background="{ThemeResource ApplicationPageBackgroundThemeBrush}">
<StackPanel x:Name="Stacky" HorizontalAlignment="Stretch" Background="Aqua" VerticalAlignment="Stretch">
<ListBox Name="listCars" ItemsSource="{x:Bind cars}" SelectionMode="Multiple" Grid.Column="0" Grid.Row="1" Background="#FFF1EFEF" Opacity="0.7" Foreground="Black" Margin="10,10,94,10" Grid.RowSpan="2">
<ListBox.ItemTemplate>
<DataTemplate x:DataType="local:Car">
<StackPanel Padding="20" BorderThickness="2" BorderBrush="Black">
<Image Width="200" Height="150" HorizontalAlignment="Left" Source="{x:Bind imgCar}" />
<TextBlock FontSize="22" HorizontalAlignment="Left" Text="{x:Bind name}" Style="{StaticResource HeaderTextBlockStyle}"/>
<TextBlock FontSize="16" HorizontalAlignment="Left"> € <Run Text="{x:Bind price}" /></TextBlock>
</StackPanel>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
<Button Content="Done Selecting" Click="Add_Click"></Button>
</StackPanel>
</Page>
MainPage.xaml.cs
public sealed partial class MainPage : Page
{
List<Car> cars = new List<Car>();
public MainPage()
{
cars.Add(new Car() { imgCar = "ms-appx:///Assets/1.jpg", name = "Car1", price = "10000" });
cars.Add(new Car() { imgCar = "ms-appx:///Assets/2.jpg", name = "Car2", price = "10001" });
cars.Add(new Car() { imgCar = "ms-appx:///Assets/3.jpg", name = "Car3", price = "10002" });
this.InitializeComponent();
}
private void Add_Click(object sender, RoutedEventArgs e)
{
List<Car> mySelectedItems = new List<Car>();
foreach (Car item in listCars.SelectedItems)
{
mySelectedItems.Add(item);
}
Frame.Navigate(typeof(Page2), mySelectedItems);
}
}
public class Car
{
public string imgCar { get; set; }
public string name { get; set; }
public string price { get; set; }
}
Page2.xaml
<Page
x:Class="App1.Page2"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="using:App1"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
mc:Ignorable="d"
Background="{ThemeResource ApplicationPageBackgroundThemeBrush}">
<Grid>
<ListBox Name="listCars" SelectionMode="Multiple" Grid.Column="0" Grid.Row="1" Background="#FFF1EFEF" Opacity="0.7" Foreground="Black" Margin="10,10,94,10" Grid.RowSpan="2">
<ListBox.ItemTemplate>
<DataTemplate x:DataType="local:Car">
<StackPanel Padding="20" BorderThickness="2" BorderBrush="Black">
<Image Width="200" Height="150" HorizontalAlignment="Left" Source="{x:Bind imgCar}" />
<TextBlock FontSize="22" HorizontalAlignment="Left" Text="{x:Bind name}" Style="{StaticResource HeaderTextBlockStyle}"/>
<TextBlock FontSize="16" HorizontalAlignment="Left"> € <Run Text="{x:Bind price}" /></TextBlock>
</StackPanel>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
</Grid>
</Page>
Page2.xaml.cs
public sealed partial class Page2 : Page
{
public Page2()
{
this.InitializeComponent();
}
protected override void OnNavigatedTo(NavigationEventArgs e)
{
var items = e.Parameter as List<Car>;
listCars.ItemsSource = items;
base.OnNavigatedTo(e);
}
}

Prism 6 Navigation Wierdness

I am still learning prism and I want to understand navigation. Having read the manual and followed #brianlagunas MVVM made simple webinar online, I decided to try a small project and see. I get a stackoverflow exception when I try to navigate to a view that has a viewmodel data-bound to some controls on my view. Here is the code below:
Profile View with empty viewmodel:
<UserControl x:Class="SampleLogin.Views.Profile"
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:prism="http://prismlibrary.com/"
prism:ViewModelLocator.AutoWireViewModel="True"
xmlns:local="clr-namespace:SampleLogin.Views"
mc:Ignorable="d"
d:DesignHeight="300" d:DesignWidth="300">
<Grid>
<TextBlock x:Name="ProfileTextBlock" HorizontalAlignment="Center" Margin="74,29,78,0" TextWrapping="Wrap" Text="PROFILE PAGE" VerticalAlignment="Top" Height="45" Width="148" FontSize="21.333" FontWeight="Bold"/>
<TextBlock x:Name="Username" HorizontalAlignment="Left" Height="26" Margin="103,96,0,0" TextWrapping="Wrap" Text="{Binding username}" VerticalAlignment="Top" Width="130"/>
<TextBlock x:Name="LoginTime" HorizontalAlignment="Left" Margin="109,152,0,0" TextWrapping="Wrap" Text="{Binding LoginTime}" VerticalAlignment="Top" Width="124" Height="33"/>
<Label x:Name="label" Content="Username :" HorizontalAlignment="Left" Margin="10,96,0,0" VerticalAlignment="Top" Width="71" FontWeight="Bold"/>
<Label x:Name="label1" Content="Login-Time:" HorizontalAlignment="Left" Height="26" Margin="12,159,0,0" VerticalAlignment="Top" Width="86" FontWeight="Bold"/>
</Grid>
but it has an empty viewmodel and it loads fine.
Here is another view with a simple form that is data-bound to its viewmodel
<UserControl x:Class="SampleLogin.Views.LoginUser"
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:prism="http://prismlibrary.com/"
prism:ViewModelLocator.AutoWireViewModel="True"
xmlns:local="clr-namespace:SampleLogin.Views"
mc:Ignorable="d"
d:DesignHeight="300" d:DesignWidth="325">
<Grid>
<Label x:Name="usernameLabel" Content="Username :" HorizontalAlignment="Left" Margin="10,93,0,0" VerticalAlignment="Top" Width="113" Height="35" FontSize="18.667" FontWeight="Bold"/>
<Label x:Name="label" Content="Password :
" HorizontalAlignment="Left" Margin="10,146,0,0" VerticalAlignment="Top" Width="100" Height="38" FontSize="18.667" FontWeight="Bold"/>
<TextBox x:Name="Username" HorizontalAlignment="Left" Height="35" Margin="132,93,0,0" TextWrapping="Wrap" VerticalAlignment="Top" Width="178" Text="{Binding Username, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}"/>
<PasswordBox x:Name="passwordBox" HorizontalAlignment="Left" Margin="132,146,0,0" VerticalAlignment="Top" Width="178" Height="35"/>
<Button x:Name="Loginbtn" Content="Login" HorizontalAlignment="Left" Margin="85,208,0,0" VerticalAlignment="Top" Width="89" Height="42" FontSize="18.667" FontWeight="Bold"
Command="{Binding LoginCommand}" CommandParameter="{Binding ElementName=passwordBox}" />
<Button x:Name="Logoutbtn" Content="Logout" HorizontalAlignment="Left" Margin="230,208,0,0" VerticalAlignment="Top" Width="80" Height="42" FontWeight="Bold" FontSize="18.667"/>
</Grid>
Here is the viewmodel its bound to: left it very simple just to understand the concept:
public class LoginUserViewModel : BindableBase
{
private AuthenticationService _auth;
public DelegateCommand<object> LoginCommand { get; set; }
public LoginUserViewModel(AuthenticationService auth)
{
_auth = auth;
LoginCommand = new DelegateCommand<object>(LoginUser, CanLoginUser);
}
private void LoginUser(object obj)
{
var passwdbox = obj as PasswordBox;
_auth.LoginUser(Username, passwdbox.SecurePassword);
}
private bool CanLoginUser(object obj)
{
var password = obj as PasswordBox;
return string.IsNullOrWhiteSpace(Username);
}
private string _username = "Enter Username here";
public string Username
{
get { return _username; }
set { SetProperty(ref _username, value); }
}
}
And here is the MainWindowViewmodel that handles the navigation using the button at the top of my mainwindow view.
public class MainWindowViewModel : BindableBase
{
IRegionManager _regions;
public DelegateCommand<string> NavigationCommand { get; set; }
public MainWindowViewModel(IRegionManager regions)
{
_regions = regions;
NavigationCommand = new DelegateCommand<string>(Navigate);
}
private void Navigate(string uri)
{
_regions.RequestNavigate("ContentRegion", uri);
}
}
And lastly, here is the MainWindowViewModel that binds to the viewmodel:
<Window x:Class="SampleLogin.Views.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:prism="http://prismlibrary.com/"
prism:ViewModelLocator.AutoWireViewModel="True"
xmlns:local="clr-namespace:SampleLogin.Views"
mc:Ignorable="d"
Title="MainWindow" Height="350" Width="525">
<Grid>
<Grid.RowDefinitions>
<RowDefinition Height="Auto" />
<RowDefinition Height="*" />
</Grid.RowDefinitions>
<StackPanel Orientation="Horizontal">
<Button Content="Login" Margin="5" Command="{Binding NavigationCommand, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}" CommandParameter="LoginUser" />
<Button Content="Home" Margin="5" Command="{Binding NavigationCommand, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}" CommandParameter="Home"/>
<Button Content="Profile" Margin="5" Command="{Binding NavigationCommand}" CommandParameter="Profile"/>
</StackPanel>
<ContentControl Grid.Row="1" prism:RegionManager.RegionName="ContentRegion" />
</Grid>
I find this very strange. The first view works when I click the buttons at the top of the screen for navigation as long as I leave the ViewModel blank. Same with the view that has the form, if I comment out the ViewModel, it navigates with no issues, showing the form and all. But if the databinding is there in the viewmodel I get the exception. Any ideas?! I am stomped and not sure where my mistake is.
Edit:
Having thought about this problem and tried to move it forward, I discovered that the error comes from the fact that my LoginUserViewModel having constructor parameters is why I am having the errors, tried using unity container in the bootstrapper register LoginUserViewmodel's dependencies but I am still getting the errors, any ideas anyone?
After doing some more searching and question asking, I got the answer to this problem. I spoke to the awesome #brianLagunas and shared my code with him and he made understand the problem I had. Its in a domain model which I didn't include in my post.
public class User : IUser
{
public User()
{
}
public User(User user){} //this is the problem line
[Required]
[Key]
public int UserId { get; set; }
[Required(ErrorMessage ="You must supply a Username")]
[DataType(DataType.Text)]
public string Username { get; private set; }
[Required(ErrorMessage = "You must enter a valid password to Login!")]
public SecureString Password { get; private set; }
[DataType(DataType.Time)]
[Required]
public TimeSpan TimeLoggedIn { get; private set; }
[DataType(DataType.Date)]
public DateTime LoginHistory { get; private set; }
public void SetUserDetails(string username, TimeSpan date, DateTime History)
{
if(string.IsNullOrWhiteSpace(username))
{
throw new ArgumentNullException("You cannot have any of the Login Fields empty..!");
}
Username = username;
TimeLoggedIn = date;
LoginHistory = History;
}
}
The second constructor was casing an infinite loop this the stack overflow error I was getting. Removing that constructor fixed the issue and all is well.

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";

Categories