I have listbox which contains buttons listed vertically with related datas as given below;
<ListBox Name="CTransactionList" Margin="0,0,0,0" >
<ListBox.ItemTemplate >
<DataTemplate>
<Button Width="400" Height="200" Background="#6A040B2E" Click="completetransact">
<Button.Content >
<StackPanel Orientation="Horizontal" Height="200" Width="400">
<Image Source="{Binding Type1}" Width="80" Height="80" VerticalAlignment="Top" Margin="0,40,0,0"/>
<StackPanel Orientation="Vertical" Height="200">
<StackPanel Orientation="Horizontal" Height="30">
<TextBlock Width="100" FontSize="22" Text="Name:" Height="30"/>
<TextBlock Width="200" FontSize="22" Text="{Binding Date1}" Height="30"/>
</StackPanel>
<StackPanel Orientation="Horizontal" Height="30">
<TextBlock Width="100" FontSize="22" Text="Difficulty:" Height="30"/>
<TextBlock Width="200" FontSize="22" Text="{Binding Amount1}" Height="30"/>
</StackPanel>
<StackPanel Orientation="Horizontal" Height="30">
<TextBlock Width="110" FontSize="22" Text="TotalTime:" Height="30"/>
<TextBlock Width="200" FontSize="22" Text="{Binding Time1}" Height="30"/>
</StackPanel>
<StackPanel Orientation="Horizontal" Height="30">
<TextBlock Width="100" FontSize="22" Text="Distance:" Height="30"/>
<TextBlock Width="200" FontSize="22" Text="{Binding Dis1}" Height="30"/>
</StackPanel>
<StackPanel Orientation="Horizontal" Height="65">
<TextBlock Width="290" FontSize="14" Text="{Binding Def1}" Height="65" TextWrapping="Wrap" FontStyle="Italic"/>
</StackPanel>
</StackPanel>
</StackPanel>
</Button.Content>
</Button>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
And I'm binding the data with such classes;
[DataContract]
public class CTransaction
{
[DataMember]
public String Date1 { get; set; }
[DataMember]
public String Amount1 { get; set; }
[DataMember]
public String Type1 { get; set; }
[DataMember]
public String Time1 { get; set; }
[DataMember]
public String Dis1 { get; set; }
[DataMember]
public String Def1 { get; set; }
[DataMember]
public String Cdate1 { get; set; }
[DataMember]
public String Strpt1 { get; set; }
[DataMember]
public String Endpt1 { get; set; }
[DataMember]
public int Index1 { get; set; }
public CTransaction(String date1, String amount1, String type1, String time1, String dis1, String def1, String cdate1, String strpt1, String endpt1,int index1)
{
this.Date1 = date1;
this.Amount1 = amount1;
this.Time1 = time1;
this.Dis1 = dis1;
this.Def1 = def1;
this.Cdate1 = cdate1;
this.Strpt1 = strpt1;
this.Endpt1 = endpt1;
this.Index1 = index1;
switch (type1)
{
case "FR":
this.Type1 = "Images/a.png";
break;
case "TA":
this.Type1 = "Images/b.png";
break;
case "DA":
this.Type1 = "Images/c.png";
break;
case "CC":
this.Type1 = "Images/mount.png";
break;
}
}
}
As shown above, I have a data binding named Index1 which indexes the button with an arbitrary integer. I want to remove a specified indexed button by user with this code;
ctransactionList.RemoveAt("index comes here");
My exact desire is to remove the clicked button,(i.e. if the second button clicked, then remove the second one). And I tried to embed some indexes(i.e. Index1) in it to remove it, I couldn't find any possible way; I also failed again.
This is the way I tried;
The removal code given above only removes the indexed item based on the whole list item count. I mean, for example, the first element always has the '0' index. It does not care my Index1 data.(I can retrieve the Index1 data with selectedButton as sender method) I wish I could have removed the button which includes the user-specified Index1 data.
How can I do this?
Thanks in advance.
(Windows Phone 7)
You can do this by adding click event handler for button:
private void Button_Click(object sender, RoutedEventArgs e)
{
var button = sender as Button;
var item = button.DataContext as CTransaction;
if (item != null)
{
ctransactionList.Remove(item);
}
}
ctransactionList should be an ObservableCollection.
Related
All the fields show ok, only Specilities string[] shows me an error... remember there are two different fids on json response we have Speciality that is OK and show OK... and we have Specilities string[] where is the problem.... check the json response
this is json response
{"_id":"5aab4c02f08d9324fc1283ec","firstName":"Carlos Alberto","lastName":"Cabezas Delgado","password":"$2a$10$BuYWhiMn.9RsBKJN7bWuguKaPAHQocd2eVQCqRaaAdmzrlPkuWYJS","identificationNumber":"0914891684","email":"carlos.cabezas#abogadosecuador.com.ec","phone":"0969922421","discount":0.5,"band":3,"city":"59cda262fe728437ce90ff81","role":"59cd270f07308946e6a494f7","__v":6,
"speciality":{"_id":"5a0a6176257e970afc9a9e7f","name":"Propiedad Intelectual","tag":"propiedad-intelectual","__v":0,"icon":"speciality_icon_jg4zpoeqoiwtuuy8jya.png","description":"Derechos de propiedad industrial, derechos de autor, patentes, modelos de utilidad, diseños industriales, marcas, indicaciones geográficas, información comercial confidencial, derecho de obtentor.","id":"5a0a6176257e970afc9a9e7f"},
"profile":"5aac7b42c02ece25becefd47","telephone":"593969922421","createdAt":"2018-08-20T03:07:03.838Z","searchTag":"CARLOSALBERTOCABEZASDELGADO","updatedAt":"2020-06-22T00:17:30.971Z","label":"CARLOS ALBERTO CABEZAS DELGADO","firstNameLabel":"Carlos Alberto","lastNameLabel":"Cabezas Delgado","plan":"5d75e792184bab2c72b3d3ab","seller":"5ad72ce8fd69e7aba867c118","telephone2":"","fax":"593969922421","isPublic":true,"isDelete":false,
"invoices":[],
"specialities":["5990d7273da48f4bd98c6918","5990d73f3da48f4bd98c691a","5a0a6055257e970afc9a9e70","5a0a6087257e970afc9a9e73","5a0a6120257e970afc9a9e7a","5a0a6166257e970afc9a9e7e","5a0a6176257e970afc9a9e7f"],
"location":{"address":"Urbanización Puerto Azul, Guayaquil, Ecuador","reference":"Puerto Azul, Vía la Costa (Edificio Torres del Edén)","latitude":-2.1902934315119,"longitude":-79.9647494058045},"status":2,"id":"5aab4c02f08d9324fc1283ec","search":"CARLOS ALBERTO CABEZAS DELGADO"
MODEL DATA
namespace App1
{
public class AbogadosMongoApi
{
[JsonProperty("_id")]
public string Idab { get; set; }
[JsonProperty("label")]
public string FirtsName { get; set; }
[JsonProperty("email")]
public string Correo { get; set; }
[JsonProperty("phone")]
public string Celular { get; set; }
[JsonProperty("password")]
public string Contrasena { get; set; }
[JsonProperty("isPublic")]
public bool Public { get; set; }
[JsonProperty("band")]
public int Band { get; set; }
[JsonProperty("plan")]
public string Plan { get; set; }
[JsonProperty("city")]
public string Ciudadperfil { get; set; }
[JsonProperty("location")]
public Location location { get; set; }
[JsonProperty("speciality")]
public Speciality speciality { get; set; }
[JsonProperty("specialities")]
public string[] Specialities { get; set; }
}
public class Speciality
{
[JsonProperty("_id")]
public string Idespecialidad { get; set; }
[JsonProperty("name")]
public string Nombrespecialidad { get; set; }
[JsonProperty("icon")]
public string Iconespecialidad { get; set; }
[JsonProperty("description")]
public string Descespecialidad { get; set; }
}
public class Location
{
[JsonProperty("address")]
public string Direccion { get; set; }
[JsonProperty("reference")]
public string Referencia { get; set; }
[JsonProperty("latitude")]
public string Latitud { get; set; }
[JsonProperty("longitude")]
public string Longitud { get; set; }
}
}
XAML
<CollectionView x:Name="abogadosrec"
BackgroundColor="#eee"
SelectionMode="Single"
SelectionChanged="CallBtnClicked"
VerticalOptions="StartAndExpand"
HorizontalOptions="CenterAndExpand">
<CollectionView.ItemTemplate>
<DataTemplate>
<SwipeView>
<SwipeView.LeftItems>
<SwipeItems>
</SwipeItems>
</SwipeView.LeftItems>
<SwipeView.RightItems>
<SwipeItems>
<SwipeItem Text="Crear Cita"
BackgroundColor="#00a783" />
</SwipeItems>
</SwipeView.RightItems>
<Grid Style="{StaticResource IndicatorLabelStyle}"
Padding="20">
<Grid.RowDefinitions>
<RowDefinition Height="Auto" />
<RowDefinition Height="Auto" />
</Grid.RowDefinitions>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="Auto" />
<ColumnDefinition Width="Auto" />
</Grid.ColumnDefinitions>
<Frame CornerRadius="100"
HeightRequest="75"
WidthRequest="75"
BorderColor="#cca876"
HorizontalOptions="Center"
Padding="0"
IsClippedToBounds="True">
<Image xct:TouchEffect.PressedScale="1.4"
Grid.RowSpan="2"
Source="{Binding Idab, StringFormat='https://abogadosecuador.com.ec/profile/picture/{0:N}'}"
Aspect="AspectFill"
HeightRequest="75"
WidthRequest="75" />
</Frame>
<Label Grid.Column="1"
Text="{Binding FirtsName}"
VerticalOptions="CenterAndExpand"
HorizontalOptions="StartAndExpand"
FontSize="Micro"
FontAttributes="Bold" />
<ListView ItemsSource="{Binding .}"
HasUnevenRows="true">
<ListView.ItemTemplate>
<DataTemplate>
<ViewCell>
<Label FontSize="3" Text="{Binding Specialities}"></Label>
</ViewCell>
</DataTemplate>
</ListView.ItemTemplate>
</ListView>
<Label Grid.Column="1"
x:Name="txtNumero" IsVisible="false"
Text="{Binding Celular, Mode=TwoWay}"
FontAttributes="Italic"
VerticalOptions="CenterAndExpand"
HorizontalOptions="StartAndExpand" />
</Grid>
</SwipeView>
</DataTemplate>
</CollectionView.ItemTemplate>
<CollectionView.Header>
<StackLayout BackgroundColor="LightGray">
<Label Margin="10,0,0,0"
Padding="10"
Text="Abogados Registrados"
FontSize="Small" />
</StackLayout>
</CollectionView.Header>
</CollectionView>
this
<ListView ItemsSource="{Binding .}"
should be
<ListView ItemsSource="{Binding Specialities}"
and this
<Label FontSize="3" Text="{Binding Specialities}" />
should be
<Label FontSize="3" Text="{Binding .}" />
It seems that I can't access it even if I put a name on it because it's inside a listview. If i wan row1 to not be visible on code behind how do i go around this?
I tried to a name for Label but I can't access it. or added I cant access on code behind.
<ListView x:Name="postListView" SeparatorVisibility="Default" HasUnevenRows="True" ItemsSource="{Binding Items}" SeparatorColor="White">
<ListView.ItemTemplate>
<DataTemplate>
<ViewCell>
<Grid BackgroundColor="Black" HorizontalOptions="CenterAndExpand"
VerticalOptions="FillAndExpand" Padding="1,2,1,0">
<Grid HorizontalOptions="CenterAndExpand"
VerticalOptions="FillAndExpand" ColumnSpacing="1" RowSpacing="1">
<Grid.RowDefinitions >
<RowDefinition Height="Auto" />
<RowDefinition Height="Auto" />
<RowDefinition Height="Auto" />
<RowDefinition Height="Auto" />
</Grid.RowDefinitions>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="120"/>
<ColumnDefinition Width="100"/>
</Grid.ColumnDefinitions>
<Label Grid.Row="0" FontSize="Medium" Grid.Column="0" Text="right tst:" HorizontalTextAlignment="Start" BackgroundColor="cornflowerblue" />
<Label Grid.Column="1" Grid.Row="0" Text="{Binding drain1vol}" HorizontalTextAlignment="Center" BackgroundColor="cornflowerblue"/>
<Label Grid.Row="1" Grid.Column="0" Text="nothing" BackgroundColor="Yellow"/>
<Label Grid.Row="1" Grid.Column="1" Text="{Binding drain2vol}" HorizontalTextAlignment="Center" BackgroundColor="Yellow" />
</Grid>
</Grid>
</ViewCell>
</DataTemplate>
</ListView.ItemTemplate>
</ListView>
//Model and Source of data
using System;
using SQLite;
using Demo.Helpers;
namespace Demo.Model
{
//this is the source of Binding
public class Post
{
//ID primary key that we will autoincrement
//These are binding source for Historypage
[PrimaryKey, AutoIncrement]
public int ID { get; set; }
public bool showLabel { get; set; } //public class model
}
}
The source is the Post class.
Binding the label's IsVisible property to the property in your model to control the visiable ability of the label.
For example,
In xaml:
<Label Grid.Column="1" Grid.Row="0" IsVisible="{Binding showLabel}" Text="{Binding drain1vol}" HorizontalTextAlignment="Center" BackgroundColor="cornflowerblue"/>
And then in your model:
public class model
{
public string drain1vol { get; set; }
public bool showLabel { get; set; }
}
When you create the dataSource, you can set the label's isVisable:
Items.Add(new model { drain1vol = "Rob Finnerty" ,showLabel= false });
Items.Add(new model { drain1vol = "Bill Wrestler", showLabel = true });
Items.Add(new model { drain1vol = "Dr. Geri-Beth Hooper", showLabel = false });
Items.Add(new model { drain1vol = "Dr. Keith Joyce-Purdy", showLabel = true });
Items.Add(new model { drain1vol = "Sheri Spruce", showLabel = false });
postListView.ItemsSource = Items;
To change the visiable ability in code behind:
void test() {
//Get the model you want to change
model.showLabel = false / true;
}
Update:
Implement the INotifyPropertyChanged interface in your model:
class model : INotifyPropertyChanged
{
private bool showLabel { get; set; }
private string drain1vol { get; set; }
protected virtual void OnPropertyChanged(string propertyName)
{
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
}
public event PropertyChangedEventHandler PropertyChanged;
public bool ShowLabel
{
set
{
if (showLabel != value)
{
showLabel = value;
OnPropertyChanged("ShowLabel");
}
}
get
{
return showLabel;
}
}
public string Drain1vol
{
set
{
if (drain1vol != value)
{
drain1vol = value;
OnPropertyChanged("Drain1vol");
}
}
get
{
return drain1vol;
}
}
}
And in your xaml, binding to ShowLabel and Drain1vol(upper-case):
<Label Grid.Column="1" Grid.Row="0" IsVisible="{Binding ShowLabel}" Text="{Binding Drain1vol}" HorizontalTextAlignment="Center" BackgroundColor="cornflowerblue"/>
All My data photo is in server Example url: http://abcd.com/images/ and i have renamed all the photos file to my album id example 1.jpg,2.jpg
and i want to display those photos using albumid in grid view
class AlbumData
{
public Int32 AlbumId { get; set; }
public String Name { get; set; }
public String Language { get; set; }
public String Actors { get; set; }
public String Director { get; set; }
public String MusicDirector { get; set; }
public String Year { get; set; }
}
private void Search_Click(object sender, RoutedEventArgs e)
{
WebClient webclient = new WebClient();
webclient.DownloadStringCompleted += new DownloadStringCompletedEventHandler(webclient_DownloadStringCompleted);
webclient.DownloadStringAsync(new Uri("http://albums.abcd.com/v1/Albums/English/1"));//--getting data using xml
}
void webclient_DownloadStringCompleted(object sender, DownloadStringCompletedEventArgs e)
{
if (e.Error != null)
{
MessageBox.Show("error");
}
XElement XmlTweet = XElement.Parse(e.Result);
listBox1.ItemsSource = from tweet in XmlTweet.Descendants("Album")
select new AlbumData()
{
Name = tweet.Element("Name").Value,
//--how to display image---//
};
}
Please help me with example
<DataTemplate>
<StackPanel>
<Image Source="{Binding ImageSource}" Height="100" Width="100" HorizontalAlignment="Center" VerticalAlignment="Center" />
<TextBlock Text="{Binding Name}" Foreground="#FFC8AB14" FontSize="15" Width="120" TextAlignment="Center" TextWrapping="Wrap" />
<!--<TextBlock Text="{Binding Message}" TextWrapping="Wrap" FontSize="8" Width="100" TextAlignment="Center" />-->
<!--<TextBlock Text="{Binding MusicDirector}" TextWrapping="Wrap" FontSize="8" Width="100" TextAlignment="Center" />-->
<!--<TextBlock Text="{Binding UserName}" Style="{StaticResource PhoneTextSubtleStyle}" Width="100" TextAlignment="Center"/>-->
</StackPanel>
</DataTemplate>
Assuming the ElementName of your images is ImageUri, you must change your ItemsSource to:
listBox1.ItemsSource =
from tweet in XmlTweet.Descendants("Album")
select new AlbumData()
{
Name = tweet.Element("Name").Value,
ImageSource = new BitmapImage(new Uri(tweet.Element("ImageUri"), UriKind.Relative));
};
AlbumData needs to be extended by
public BitmapImage ImageSource { get; set; }
I have a pivot control, the items are binded from a list, I want to make the pivot header look like a page number, look like this : (1/20) (2/20) (3/20) .... This is my xaml:
<Grid x:Name="LayoutRoot">
<Grid.Background>
<ImageBrush ImageSource="/Images/PivotBackground.png"/>
</Grid.Background>
<!--Pivot Control-->
<controls:Pivot x:Name="newsPivot" ItemsSource="{Binding LatestArticles}" Margin="0,68,0,0">
<!--Pivot item one-->
<controls:Pivot.HeaderTemplate>
<DataTemplate>
<TextBlock Text="1" FontSize="30" Foreground="White" TextWrapping="Wrap"/>
</DataTemplate>
</controls:Pivot.HeaderTemplate>
<controls:Pivot.ItemTemplate>
<DataTemplate>
<ScrollViewer>
<Grid>
<StackPanel>
<TextBlock Text="{Binding title}" FontSize="30" Foreground="Black" TextWrapping="Wrap"
Grid.Row="1"
Grid.Column="0"
Width="425"
Margin="10,0,0,0"/>
</StackPanel>
<StackPanel>
<Image delay:LowProfileImageLoader.UriSource="{Binding thumbnail, StringFormat='http://digitaledition.philstar.com/newsrepository/newsarticles/thumbs/images/\{0\}'}"
Margin="18,100,0,0"
Grid.Column="0"
Grid.Row="2"
HorizontalAlignment="Left"
Width="150"
Height="175"
Stretch="UniformToFill" />
</StackPanel>
<StackPanel>
<TextBlock Text="{Binding author, StringFormat='By \{0\}'}" TextWrapping="Wrap" FontSize="22"
Grid.Column="1"
Width="220"
Foreground="Gray"
Margin="120,135,0,0"/>
</StackPanel>
<StackPanel>
<TextBlock Text="{Binding dateFormatted}" TextWrapping="Wrap" FontSize="20"
Grid.Column="1"
Width="240"
Foreground="Gray"
Margin="140,210,0,0"/>
</StackPanel>
<StackPanel>
<TextBlock Text="{Binding content}" TextWrapping="Wrap" FontSize="24"
Grid.Column="1"
Width="425"
Foreground="Black"
Margin="10,325,0,0"/>
</StackPanel>
</Grid>
</ScrollViewer>
</DataTemplate>
</controls:Pivot.ItemTemplate>
<!--Pivot item two-->
</controls:Pivot>
</Grid>
Spent hours of searching on google but no solution found. Please someone help me with my project. thanks in advance!
Code behind Xaml:
public NewsPivot()
{
InitializeComponent();
var y = new WebClient();
Observable
.FromEvent<DownloadStringCompletedEventArgs>(y, "DownloadStringCompleted")
.Subscribe(r =>
{
var des =
JsonConvert.DeserializeObject<List<LatestArticles>>(r.EventArgs.Result);
newsPivot.ItemsSource = des.Where(s=> s.category_id == "1");
});
y.DownloadStringAsync(
new Uri("http://sample.json.com/mobile/articles?"));
}
LatestArticle.cs :
public class LatestArticles
{
public string id { get; set; }
public string title { get; set; }
public string thumbnail { get; set; }
public string hits { get; set; }
public string thumbCaption { get; set; }
public string category_id { get; set; }
public string dateFormatted { get; set; }
public string author { get; set; }
}
You would have to Bind the Text of the Header to a property on your Articles object. This propery would be the page index of the article.
<controls:Pivot.HeaderTemplate>
<DataTemplate>
<TextBlock Text="{Binding PageNumber}" FontSize="30" Foreground="White" TextWrapping="Wrap"/>
</DataTemplate>
</controls:Pivot.HeaderTemplate>
You would then need to set the page number of the Article when it is added to the LatestArticles collection.
LatestArticles.Add(article);
article.PageNumber = LatestArticles.Count +1;
Another option is to use a value converter. This option would require you to have access to the LatestArticles somehow.
<controls:Pivot.HeaderTemplate>
<DataTemplate>
<TextBlock Text="{Binding Converter={StaticResource PageNumberConverter}}" FontSize="30" Foreground="White" TextWrapping="Wrap"/>
</DataTemplate>
</controls:Pivot.HeaderTemplate>
The ValueConverter is very simple
public class PageNumberConverter : IValueConverter
{
public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
// Assumes that the App.xaml.cs class has a static ViewModel property
return App.ViewModel.LatestArticles.IndexOf(value) + 1;
}
public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
throw new NotImplementedException();
}
}
So, I have a code:
<tool:LongListSelector x:Name="citiesListGropus" Background="Transparent"
ItemTemplate="{StaticResource citiesItemTemplate}"
GroupHeaderTemplate="{StaticResource groupHeaderTemplate}"
GroupItemTemplate="{StaticResource groupItemTemplate}" Height="468" Margin="0,68,0,0">
<tool:LongListSelector.GroupItemsPanel>
<ItemsPanelTemplate>
<tool:WrapPanel/>
</ItemsPanelTemplate>
</tool:LongListSelector.GroupItemsPanel>
</tool:LongListSelector>
And have a DataTemplate:
<DataTemplate x:Key="groupHeaderTemplate" x:Name="groupHeaderTemplateName">
<Border Background="{StaticResource PhoneAccentBrush}" Width="75" Height="75" Margin="-333, 15, 0, 15" x:Name="groupHeaderName">
<TextBlock Text="{Binding Title}" FontSize="40" Foreground="White" Margin="15, 15, 0, 0"/>
</Border>
</DataTemplate>
How can I change a property Visibility of Border in DataTemplate ? I want to hide DataTemplate. But I can't bind my data to a property such as TextBlock Text="{Binding Title}", because I make binding data once, then I need to change some properties after data binding.
Any Ideas?
UPDATE 1
So, my main goal is filter the list of cities. I want to filter them by name.
My algorithm:
1) I get data from WebService.
2) Load my ViewModel
if (!App.CitiesViewModel.IsDataLoaded)
{
App.CitiesViewModel.LoadData(serviceResponse.Result);
}
3) Group the cities by name. My code like this code.
This is important, especially for LongListSeletstor I have to use templates.
Ok, my data ready. Now I do not need a web service.
<!-- The template for city items -->
<DataTemplate x:Key="citiesItemTemplate">
<StackPanel Name="PlacePanel"
Orientation="Horizontal" Margin="0,0,0,17"
Tag="{Binding Id}" Visibility="{Binding IsVisibility}">
<Image Height="75" Width="75" HorizontalAlignment="Left" Margin="12,0,9,0" Name="Image" Stretch="Fill" VerticalAlignment="Top" Source="{Binding Image}"/>
<StackPanel Width="311">
<TextBlock Text="{Binding Name}" TextWrapping="Wrap" Style="{StaticResource PhoneTextExtraLargeStyle}"/>
</StackPanel>
</StackPanel>
</DataTemplate>
I have TextBox, when I type name of a city - unnecessary cities hide. I can use data binding and INotifyPropertyChanged, so I can hide cities.
private void TextBox_TextChanged(object sender, TextChangedEventArgs e)
{
TextBox name = (TextBox)sender;
foreach(var place in App.CitiesViewModel.Items
.Where(city => (city.Name.Contains(name.Text)) && (city.IsShow == true)))
{
city.IsVisibility = Visibility.Visible;
}
foreach (var city in App.CitiesViewModel.Items
.Where(city => !city.Name.Contains(name.Text)))
{
city.IsVisibility = Visibility.Collapsed;
}
}
But I have some problems, I can't hide this DataTemplate when I search cities:
<DataTemplate x:Key="groupHeaderTemplate" x:Name="groupHeaderTemplateName">
<Border Background="{StaticResource PhoneAccentBrush}" Width="75" Height="75" Margin="-333, 15, 0, 15" x:Name="groupHeaderName">
<TextBlock Text="{Binding Title}" FontSize="40" Foreground="White" Margin="15, 15, 0, 0"/>
</Border>
</DataTemplate>
When I type name of a cities I want hide GroupHeaderTemplate. When TextBox lost focus show GroupHeaderTemplate.
I borrowed this picture here.
Update 2
My mistake was that I did not use PropertyChangedEventHandler. After adding this to GroupCity property and implementing an interface INotifyPropertyChanged I can change property Data Template after data binding.
private IList<Group<City>> citiesCollectionGroup;
var cityByName = from city in App.ViewModel.Items
group city by Convert.ToString(City.Name[0]).ToLower()
into c orderby c.Key select new
GroupCity<CitiesViewModel>(Convert.ToString(c.Key[0]).ToLower(), c);
citiesCollectionGroup = cityByName.ToList();
this.citiesListGropus.ItemsSource = citiesCollectionGroup;
public class GroupCity<T> : IEnumerable<T>, INotifyPropertyChanged
{
public GroupCity(string name, IEnumerable<T> items)
{
this.Title = name;
this.IsVisibility = Visibility.Visible;
this.Items = new List<T>(items);
}
public override bool Equals(object obj)
{
GroupCity<T> that = obj as GroupCity<T>;
return (that != null) && (this.Title.Equals(that.Title));
}
public string Title
{
get;
set;
}
private Visibility _isVisibility;
public Visibility IsVisibility
{
get
{
return _isVisibility;
}
set
{
_isVisibility = value;
NotifyPropertyChanged("IsVisibility");
}
}
public IList<T> Items
{
get;
set;
}
public event PropertyChangedEventHandler PropertyChanged;
private void NotifyPropertyChanged(String propertyName)
{
PropertyChangedEventHandler handler = PropertyChanged;
if (null != handler)
{
handler(this, new PropertyChangedEventArgs(propertyName));
}
}
#region IEnumerable<T> Members
public IEnumerator<T> GetEnumerator()
{
return this.Items.GetEnumerator();
}
#endregion
#region IEnumerable Members
System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator()
{
return this.Items.GetEnumerator();
}
#endregion
}
Xaml code:
<DataTemplate x:Key="groupHeaderTemplate" x:Name="groupHeaderTemplateName">
<Border Background="{StaticResource PhoneAccentBrush}" Width="75" Height="75" Margin="-333, 15, 0, 15" x:Name="groupHeaderName" Visibility="{Binding IsVisibility}">
<TextBlock Text="{Binding Title}" FontSize="40" Foreground="White" Margin="15, 15, 0, 0"/>
</Border>
</DataTemplate>
Now we can change Visibility groupHeaderTemplate.
private void TextBox_TextChanged(object sender, TextChangedEventArgs e)
{
foreach (GroupCity<CitiesViewModel> city in citiesCollectionGroup)
{
city.IsVisibility = Visibility.Collapsed;
}
//
}
private void SearchText_LostFocus(object sender, RoutedEventArgs e)
{
foreach (GroupCity<CitiesViewModel> city in citiesCollectionGroup)
{
city.IsVisibility = Visibility.Visible;
}
//
}
You can write your own simple DataTemplateSelector to do this. Check this out for more information.
With "How can I change a property Visibility of Border in DataTemplate ? I want to hide DataTemplate. " I understand that you want to change the visibility of an item based on a property, see example below.
(If the code below isn't quite the solution you are looking for please provide some more information about what you are trying to achieve. Re-reading your question and the comments I got on this example I doubt this is what you want to do, but I don't want to guess so I'm simply answering my interpretation of your question).
With bindings you can:
Bind the visibility property directly to a a property of type Visibility (example with listbox and Person1)
Bind the Visibility property to a boolean property, and use a converter to convert that to the Visibility type (listbox2 and Person2 + BoolToVis class).
There are more ways, but this are the two most simple to implement in my opinion.¨
result of code below:
View:
<phone:PhoneApplicationPage
x:Class="VisibilityWP.MainPage"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:phone="clr-namespace:Microsoft.Phone.Controls;assembly=Microsoft.Phone"
xmlns:shell="clr-namespace:Microsoft.Phone.Shell;assembly=Microsoft.Phone"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
mc:Ignorable="d" d:DesignWidth="480" d:DesignHeight="768"
FontFamily="{StaticResource PhoneFontFamilyNormal}"
FontSize="{StaticResource PhoneFontSizeNormal}"
Foreground="{StaticResource PhoneForegroundBrush}"
SupportedOrientations="Portrait" Orientation="Portrait"
xmlns:VisibilityWP="clr-namespace:VisibilityWP"
shell:SystemTray.IsVisible="True">
<Grid x:Name="LayoutRoot" Background="Transparent">
<Grid.RowDefinitions>
<RowDefinition Height="Auto"/>
<RowDefinition Height="*"/>
</Grid.RowDefinitions>
<StackPanel x:Name="TitlePanel" Grid.Row="0" Margin="12,17,0,28">
<TextBlock x:Name="ApplicationTitle" Text="MY APPLICATION" Style="{StaticResource PhoneTextNormalStyle}"/>
<TextBlock x:Name="PageTitle" Text="page name" Margin="9,-7,0,0" Style="{StaticResource PhoneTextTitle1Style}"/>
</StackPanel>
<Grid x:Name="ContentPanel" Grid.Row="1" Margin="12,0,12,0">
<Grid.Resources>
<VisibilityWP:BoolToVis x:Key="BooleanToVisibilityConverter" />
</Grid.Resources>
<StackPanel>
<ListBox x:Name="listBox" Height="300">
<ListBox.ItemTemplate>
<DataTemplate>
<Border Width="200" Visibility="{Binding Visibility}" Background="Blue">
<TextBlock Text="{Binding Name}" FontSize="40" Foreground="White" Margin="15, 15, 0, 0"/>
</Border>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
<ListBox x:Name="listBox2" Height="300">
<ListBox.ItemTemplate>
<DataTemplate>
<Border Width="200" Visibility="{Binding ShowBorder, Converter={StaticResource BooleanToVisibilityConverter}}" Background="Red">
<TextBlock Text="{Binding Name}" FontSize="40" Foreground="White" Margin="15, 15, 0, 0"/>
</Border>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
</StackPanel>
</Grid>
</Grid>
Code behind:
using System;
using System.Collections.Generic;
using System.Windows;
using System.Windows.Data;
namespace VisibilityWP
{
public partial class MainPage
{
public MainPage()
{
InitializeComponent();
DataContext = this;
listBox.ItemsSource = new List<Person1>
{
new Person1 {Name = "Iris", Visibility = Visibility.Visible},
new Person1 {Name = "Somebody", Visibility = Visibility.Collapsed},
new Person1 {Name = "Peter", Visibility = Visibility.Visible},
};
listBox2.ItemsSource = new List<Person2>
{
new Person2 {Name = "Iris", ShowBorder = true},
new Person2 {Name = "Mia", ShowBorder = true},
new Person2 {Name = "Somebody", ShowBorder = false}
};
}
}
public class Person1
{
public string Name { get; set; }
public Visibility Visibility { get; set; }
}
public class Person2
{
public string Name { get; set; }
public bool ShowBorder { get; set; }
}
public sealed class BoolToVis : IValueConverter
{
public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
return (value is bool && (bool)value) ? Visibility.Visible : Visibility.Collapsed;
}
public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
return value is Visibility && (Visibility)value == Visibility.Visible;
}
}
}