I have a listbox containing a choice of text answers taken from the database and containing html languages, such as: <p>, etc. I want to display it so that the html language is not displayed. I tried to display it in the webview, but <p>, etc. is still visible.
XAML:
<ListBox Name="ListOption" Grid.Row="1" Margin="10,20,10,0" Height="auto" xmlns:m="using:KipinSchool_Win10.TryoutData.Models" SelectionChanged="ListAlternatives_SelectionChanged" VerticalAlignment="Stretch" HorizontalAlignment="Stretch">
<ListBox.ItemTemplate>
<DataTemplate x:DataType="m:DBOption">
<StackPanel Orientation="Horizontal">
<WebView Margin="10,10,10,10" local:MyProperties.HtmlString="{Binding Option}" MinHeight="40" MaxHeight="300" HorizontalAlignment="Stretch" Tag="{Binding OID}"/>
<TextBlock Text="{Binding Option}" Tag="{Binding OID}" FontSize="19"/>
</StackPanel>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
Code:
string strA = #"SELECT DISTINCT* FROM DBOption WHERE QID='" + question[0] + "'";
var alternative = objConn.Prepare(strA);
ObservableCollection<DBOption> Items = new ObservableCollection<DBOption>();
int i = 0;
while (alternative.Step() == SQLiteResult.ROW)
{
Items.Add(new DBOption(alternative[0].ToString(), alternative[1].ToString(), alternative[2].ToString(), alternative[3].ToString()));
}
Binding myBinding = new Binding();
myBinding.Source = Items;
ListOption.SetBinding(ItemsControl.ItemsSourceProperty, myBinding);
How to handle it?
I tried to display it in the webview, but etc. is still visible. XAML:
I could reproduce your issue, the problem is that you have not set width and height property for WebView. And html string does not contain the content height. So the WebView will not display correctly. Please modify the code like the following.
<ListBox.ItemTemplate>
<DataTemplate >
<StackPanel Orientation="Horizontal">
<WebView Margin="10,10,10,10"
local:MyProperties.HtmlString="{Binding Option}"
Height="400" Width="200"
HorizontalAlignment="Stretch"
Tag="{Binding OID}"/>
</StackPanel>
</DataTemplate>
</ListBox.ItemTemplate>
Related
I want to create a gallery image on the first page contains a thumbnail for that category and when thumbnail is selected, it will open the image and description of the selected image in flipview (can be swipe to the right and to the left when thumbnail is selected for the image before and after). I have difficulties when applying it into flipview.
Code:
MainPage XAML
<GridView
x:Name="itemGridView"
AutomationProperties.AutomationId="ItemGridView"
AutomationProperties.Name="Grouped Items"
Grid.RowSpan="3"
Padding="116,137,40,46"
ItemsSource="{Binding Source={StaticResource groupedItemsViewSource}}"
SelectionMode="None"
IsSwipeEnabled="false"
IsItemClickEnabled="True"
ItemClick="ItemView_ItemClick" Background="#FF6996D1" >
<GridView.ItemTemplate>
<DataTemplate>
<Grid HorizontalAlignment="Left" Width="240" Height="180">
<Border>
<Image Source="{Binding ImagePath}" Stretch="Uniform" AutomationProperties.Name="{Binding Title}"/>
</Border>
</Grid>
</DataTemplate>
</GridView.ItemTemplate>
<GridView.ItemsPanel>
<ItemsPanelTemplate>
<ItemsWrapGrid GroupPadding="0,0,70,0"/>
</ItemsPanelTemplate>
</GridView.ItemsPanel>
</GridView>
MainPage:
public MainPage()
{
this.InitializeComponent();
Gallery();
}
private async void Gallery()
{
var sampleDataGroups = await DataItemSource.GetGroupsAsync();
this.DefaultViewModel["Groups"] = sampleDataGroups;
}
void ItemView_ItemClick(object sender, ItemClickEventArgs e)
{
// Navigate to the appropriate destination page, configuring the new page
// by passing required information as a navigation parameter
var itemId = ((SampleDataItem)e.ClickedItem).UniqueId;
this.Frame.Navigate(typeof(ItemDetailPage), itemId);
}
ItemDetailPage XAML:
<Grid Grid.Row="1" x:Name="contentRegion" Background="#FF6996D1">
<Image Source="{Binding ImagePath}" HorizontalAlignment="Left" Height="559" Margin="84,20,0,49" VerticalAlignment="Center" Width="732"/>
<ScrollViewer x:Name="myScroll" VerticalScrollBarVisibility="Auto" Margin="852,60,50,91" VerticalScrollMode="Auto" HorizontalScrollBarVisibility="Auto">
<TextBlock Text="{Binding Description}" TextWrapping="Wrap" Height="2210" Width="425" FontSize="27" TextAlignment="Justify" />
</ScrollViewer>
</Grid>
ItemDetailPage Code:
public ItemDetailPage()
{
this.InitializeComponent();
this.navigationHelper = new NavigationHelper(this);
this.navigationHelper.LoadState += navigationHelper_LoadState;
}
private async void navigationHelper_LoadState(object sender, LoadStateEventArgs e)
{
// TODO: Create an appropriate data model for your problem domain to replace the sample data
var item = await DataItemSource.GetItemAsync((String)e.NavigationParameter);
this.DefaultViewModel["Item"] = item;
}
protected override void OnNavigatedTo(NavigationEventArgs e)
{
navigationHelper.OnNavigatedTo(e);
}
protected override void OnNavigatedFrom(NavigationEventArgs e)
{
navigationHelper.OnNavigatedFrom(e);
}
How do I apply flipview on ItemDetailPage?
Note:
For more code detail you can view the sample
To apply flipview on ItemDetailPage, we can add FlipView under "contentRegion" and set the Image and ScrollViewer as FlipView's ItemTemplate like following:
<Grid x:Name="contentRegion" Grid.Row="1" Background="#FF6996D1">
<FlipView ItemsSource="{Binding Group.Items}" SelectedItem="{Binding Item, Mode=TwoWay}">
<FlipView.ItemTemplate>
<DataTemplate>
<Grid>
<Image Width="732"
Height="559"
Margin="84,20,0,49"
HorizontalAlignment="Left"
VerticalAlignment="Center"
Source="{Binding ImagePath}" />
<ScrollViewer x:Name="myScroll"
Margin="852,60,50,91"
HorizontalScrollBarVisibility="Auto"
VerticalScrollBarVisibility="Auto"
VerticalScrollMode="Auto">
<TextBlock Width="425"
Height="2210"
FontSize="27"
Text="{Binding Description}"
TextAlignment="Justify"
TextWrapping="Wrap" />
</ScrollViewer>
</Grid>
</DataTemplate>
</FlipView.ItemTemplate>
</FlipView>
</Grid>
And in code-behind, set the data source like following:
private async void navigationHelper_LoadState(object sender, LoadStateEventArgs e)
{
// TODO: Create an appropriate data model for your problem domain to replace the sample data
var item = await DataItemSource.GetItemAsync((String)e.NavigationParameter);
var group = await DataItemSource.GetGroupByItemAsync(item);
this.DefaultViewModel["Group"] = group;
this.DefaultViewModel["Item"] = item;
}
Here I add a GetGroupByItemAsync(SampleDataItem item) method in DataItemSource which can retrieve the group according to the item.
public static async Task<SampleDataGroup> GetGroupByItemAsync(SampleDataItem item)
{
await _DataItemSource.GetSampleDataAsync();
// Simple linear search is acceptable for small data sets
var matches = _DataItemSource.Groups.Where(group => group.Items.Contains(item));
if (matches.Count() == 1) return matches.First();
return null;
}
Besides these, we also need to remove DataContext="{Binding Item}" form root Grid and put in in <Grid Background="#FF6996D1" DataContext="{Binding Item}">.
After this, the FlipView should be able to work. However here is a strange behavior, if we select the second or third image, the previous image in flip view won't show like following
We are investigating on this issue. As a workaround, we can disable FlipView's virtualization by changing its ItemsPanel like:
<FlipView.ItemsPanel>
<ItemsPanelTemplate>
<StackPanel Orientation="Horizontal" />
</ItemsPanelTemplate>
</FlipView.ItemsPanel>
The complete XAML code of ItemDetailPage might like:
<Page x:Class="ImageGalerry.ItemDetailPage"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:common="using:ImageGalerry.Common"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:data="using:ImageGalerry.Data"
xmlns:local="using:ImageGalerry"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
DataContext="{Binding DefaultViewModel,
RelativeSource={RelativeSource Self}}"
mc:Ignorable="d">
<Grid d:DataContext="{Binding Groups[0].Items[0], Source={d:DesignData Source=/DataModel/DataItem.json, Type=data:DataItemSource}}" Background="{ThemeResource ApplicationPageBackgroundThemeBrush}">
<Grid.RowDefinitions>
<RowDefinition Height="140" />
<RowDefinition Height="*" />
</Grid.RowDefinitions>
<!-- Back button and page title -->
<Grid Background="#FF6996D1" DataContext="{Binding Item}">
<Grid.ColumnDefinitions>
<ColumnDefinition Width="1366" />
</Grid.ColumnDefinitions>
<Button x:Name="backButton"
Margin="39,59,0,0"
VerticalAlignment="Top"
AutomationProperties.AutomationId="BackButton"
AutomationProperties.ItemType="Navigation Button"
AutomationProperties.Name="Back"
Command="{Binding NavigationHelper.GoBackCommand,
ElementName=pageRoot}"
Style="{StaticResource NavigationBackButtonNormalStyle}" />
<TextBlock x:Name="pageTitle"
Margin="120,40,30,40"
VerticalAlignment="Top"
IsHitTestVisible="false"
Style="{StaticResource HeaderTextBlockStyle}"
Text="{Binding Title}"
TextWrapping="NoWrap" />
<!--<MediaElement x:Name="mediaplayer" Source="images/ost.mp3" AudioCategory="BackgroundCapableMedia" />
<Button x:Name="PlayButton" Content="Stop" Click="PlayButton_Click" Margin="1274,72,0,30" />-->
</Grid>
<Grid x:Name="contentRegion" Grid.Row="1" Background="#FF6996D1">
<FlipView ItemsSource="{Binding Group.Items}" SelectedItem="{Binding Item, Mode=TwoWay}">
<FlipView.ItemsPanel>
<ItemsPanelTemplate>
<StackPanel Orientation="Horizontal" />
</ItemsPanelTemplate>
</FlipView.ItemsPanel>
<FlipView.ItemTemplate>
<DataTemplate>
<Grid>
<Image Width="732"
Height="559"
Margin="84,20,0,49"
HorizontalAlignment="Left"
VerticalAlignment="Center"
Source="{Binding ImagePath}" />
<ScrollViewer x:Name="myScroll"
Margin="852,60,50,91"
HorizontalScrollBarVisibility="Auto"
VerticalScrollBarVisibility="Auto"
VerticalScrollMode="Auto">
<TextBlock Width="425"
Height="2210"
FontSize="27"
Text="{Binding Description}"
TextAlignment="Justify"
TextWrapping="Wrap" />
</ScrollViewer>
</Grid>
</DataTemplate>
</FlipView.ItemTemplate>
</FlipView>
</Grid>
</Grid>
</Page>
Please note that disabling UI virtualization for FlipView may negatively impact performance especially when there are a lot of images. If you have a lot of images, you can try to use incremental loading and data virtualization.
I'm having some trouble getting my semantic zoom bind correctly to my CollectionViewSource. I'm pretty new to MVVM, so I'm not sure i have stuff setup correctly.
View Model
private async void GetData()
{
// Simulate pulling data from api
string response;
StorageFile file = await StorageFile.GetFileFromApplicationUriAsync(new Uri(#"ms-appx:///DesignData/GetLive.json"));
using (StreamReader sRead = new StreamReader(await file.OpenStreamForReadAsync()))
response = await sRead.ReadToEndAsync();
// Deserialize data to class
LiveStreamModel liveGames = JsonConvert.DeserializeObject<LiveStreamModel>(response);
Schedules = liveGames.schedule;
// Group data by event
var groupData = liveGames.schedule.GroupBy(a => a.#event);
// Set cvs source to grouped data
ScheduleSource = new CollectionViewSource() { IsSourceGrouped = true, Source = groupData };
}
private CollectionViewSource scheduleSource;
public CollectionViewSource ScheduleSource
{
get
{
return scheduleSource;
}
set
{
scheduleSource = value;
RaisePropertyChanged("ScheduleSource");
}
}
View
Page.Resources>
<DataTemplate x:Key="ZoomedInTemplate">
<StackPanel Orientation="Horizontal" MinWidth="200" Margin="12,6,0,6">
<!--<Image Source="{Binding ImagePath}" Height="80" Width="80"/>-->
<StackPanel Margin="20,0,0,0">
<TextBlock Text="{Binding homeTeam}" Style="{StaticResource BaseTextBlockStyle}"/>
<TextBlock Text="{Binding awayTeam}" TextWrapping="Wrap" HorizontalAlignment="Left" Width="300"
Style="{StaticResource BodyTextBlockStyle}"/>
</StackPanel>
</StackPanel>
</DataTemplate>
<DataTemplate x:Key="ZoomedInGroupHeaderTemplate">
<TextBlock Text="{Binding event}" Foreground="{ThemeResource ApplicationForegroundThemeBrush}"
Style="{StaticResource SubtitleTextBlockStyle}"/>
</DataTemplate>
<DataTemplate x:Key="ZoomedOutTemplate">
<TextBlock Text="{Binding event}" Style="{StaticResource SubtitleTextBlockStyle}"/>
</DataTemplate>
</Page.Resources>
<Grid Background="{ThemeResource ApplicationPageBackgroundThemeBrush}">
<SemanticZoom x:Name="GetLiveZoom" >
<SemanticZoom.ZoomedInView>
<GridView x:Name="GetLiveGrid" ItemsSource="{Binding ScheduleSource.View}" ItemTemplate="{StaticResource ZoomedInTemplate}" SelectionMode="Single"
ScrollViewer.IsHorizontalScrollChainingEnabled="False">
<GridView.GroupStyle>
<GroupStyle HeaderTemplate="{StaticResource ZoomedInGroupHeaderTemplate}" />
</GridView.GroupStyle>
</GridView>
</SemanticZoom.ZoomedInView>
<SemanticZoom.ZoomedOutView>
<GridView x:Name="GetLiveList" ItemsSource="{Binding ScheduleSource.View.CollectionGroups}" ItemTemplate="{StaticResource ZoomedOutTemplate}" SelectionMode="None"
ScrollViewer.IsVerticalScrollChainingEnabled="False"/>
</SemanticZoom.ZoomedOutView>
</SemanticZoom>
</Grid>
When debugging, my data is getting grouped properly by #event, but setting the source of the cvs to the grouped data and binding that to the semantic zoom control results in nothing showing up.
You need to fix the following data binding:
1) For ZoomedInGroupHeaderTemplate, because the Source is grouped data, so if you want to show the group name in ZoomedInView, set data binding for Key property:
<DataTemplate x:Key="ZoomedInGroupHeaderTemplate">
<TextBlock Text="{Binding Key}" Foreground="{ThemeResource ApplicationForegroundThemeBrush}"
Style="{StaticResource SubtitleTextBlockStyle}"/>
</DataTemplate>
2) For ZoomedOutTemplate, the Source is ICollectionView.CollectionGroups, ref MSDN -> ICollectionViewGroup interface
We need to use ICollectionViewGroup.Group property to get group name in ZoomedOutView:
<DataTemplate x:Key="ZoomedOutTemplate">
<TextBlock Text="{Binding Group.Key}" Style="{StaticResource SubtitleTextBlockStyle}"/>
</DataTemplate>
Check my completed sample in Github
Screenshot for ZoomedInView:
Screenshot for ZoomedOutView:
Im trying to add items to the combo box from the code behind to the item template but im getting null. This is what I have so far:
XAML:
<ListBox x:Name="lsbCiertoYFalsoInsideTemplate" Margin="40,0,0,0" ItemTemplate="{StaticResource CiertoYFalsoExcerciseDataTemplate}"/>
App.xaml:
<DataTemplate x:Key="CiertoYFalsoExcerciseDataTemplate">
<Grid>
<StackPanel x:Name="stckCiertoYFalsoInsideTemplate" Margin="0" Orientation="Vertical" Width="1100">
<StackPanel x:Name="stckPreguntasCiertoYFalso" Orientation="Horizontal">
<Grid Height="50" Width="65" DataContext="{Binding CustomValueList}" VerticalAlignment="Top">
<ComboBox x:Name="cbExercises" Style="{StaticResource SA_ComboBoxStyle}" ItemsSource="{Binding CustomOption}" BorderBrush="#CC8C8C8C" VerticalAlignment="Top">
</ComboBox>
</Grid>
<TextBlock HorizontalAlignment="Center" Margin="5,3,0,0" TextWrapping="Wrap" Text="{Binding QuestionNumber}" VerticalAlignment="Top" FontWeight="Bold" Foreground="Black" Width="26" FontFamily="{Binding FontFamily, Source={StaticResource TextBlockStyleManager}}" FontSize="{Binding FontSize, Source={StaticResource TextBlockStyleManager}}"/>
<TextBlock TextWrapping="Wrap" Text="{Binding Question}" Foreground="Black" VerticalAlignment="Top" FontSize="{Binding FontSize, Source={StaticResource TextBlockStyleManager}}" Margin="10,3,0,0" Width="968" FontFamily="{Binding FontFamily, Source={StaticResource TextBlockStyleManager}}"/>
</StackPanel>
</StackPanel>
</Grid>
</DataTemplate>
The error im getting is object out of range.
Code:
private void ComboBoxExercises()
{
ComboBox comboBox = new ComboBox();
ComboboxItem item = new ComboboxItem();
item.Text = "A";
comboBox = (ComboBox)lsbCiertoYFalsoInsideTemplate.FindName("cbExercises");
comboBox.SelectedIndex = 0;
comboBox.Items.Add(item);
}
public class ComboboxItem
{
public string Text { get; set; }
public override string ToString()
{
return Text;
}
}
There's a disconnect in what you're trying to do here. You've specified an ItemTemplate - which defines how each item in the list will look.
But then you're trying to get one single ComboBox back out via the FindName function. Which leads me to believe that you're really intending to set the Template, not the ItemTemplate.
That said, I think the error you're getting is because you're setting the SelectedIndex to 0 when the ComboBox has no items in it. You're telling it to select the first one, but there's nothing to select. You should add the item first, then select it.
I'm trying to create an ItemTemplate for a ListBox programmatically but it doesn't work. I know in XAML I can have something like:
<ListBox x:Name="listbox" BorderThickness="0" Margin="6" Height="400">
<ListBox.ItemTemplate>
<DataTemplate>
<TextBlock Margin="0" Background="Red" Foreground="White" FontSize="18" Text="{Binding}" />
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
But when I'm trying to have the above result programmatically I face a problem which is binding the TextBox.TextProperty:
var textblock = new FrameworkElementFactory(typeof(TextBlock));
// Setting some properties
textblock.SetValue(TextBlock.TextProperty, ??);
var template = new ControlTemplate(typeof(ListBoxItem));
template.VisualTree = textblock;
Please help me on this issue. I couldn't find anything on the web about it.
Thanks in advance.
Try use dot . in Binding, this is the equivalent of {Binding}.
Example:
XAML
<Window x:Class="MyNamespace.MainWindow"
...
Loaded="Window_Loaded">
<ListBox Name="MyListBox" ... />
</Window>
Code-behind
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
}
private void Window_Loaded(object sender, RoutedEventArgs e)
{
var textBlockFactory = new FrameworkElementFactory(typeof(TextBlock));
textBlockFactory.SetValue(TextBlock.TextProperty, new Binding(".")); // Here
textBlockFactory.SetValue(TextBlock.BackgroundProperty, Brushes.Red);
textBlockFactory.SetValue(TextBlock.ForegroundProperty, Brushes.Wheat);
textBlockFactory.SetValue(TextBlock.FontSizeProperty, 18.0);
var template = new DataTemplate();
template.VisualTree = textBlockFactory;
MyListBox.ItemTemplate = template;
}
}
Try this, by binding the "listbox" with ItemsSource and specify the datatemplate below like if you want to bind name then just write {Binding Name}
<ListBox x:Name="listbox" BorderThickness="0" Margin="6" Height="400" ItemsSource="{Binding}">
<ListBox.ItemTemplate>
<DataTemplate>
<TextBlock Margin="0" Background="Red" Foreground="White" FontSize="18" Text="{Binding Name}" />
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
I m new to wpf.In order to get check list box functionality ,I have added below xaml to my code,but there is no output in my screen.only blank,what it could be?
<TabItem Header="Samples" >
<ListBox Margin="10" Width="373" Height="236">
<ListBox.ItemTemplate>
<DataTemplate>
<StackPanel Orientation="Horizontal">
<TextBlock Text="MyText"/>
<CheckBox IsChecked="False"/>
</StackPanel>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
</TabItem>
just have a look at this basic sample
http://merill.net/2009/10/wpf-checked-listbox/
List box is a bit wired for such task..Have a look at ItemsControl.
Here is the code i use:
<ItemsControl
ItemsSource="{Binding ***}" IsTabStop="False">
<ItemsControl.ItemTemplate>
<DataTemplate>
<CheckBox
Content="{Binding Name}"
IsChecked="{Binding IsSelected}" />
</DataTemplate>
</ItemsControl.ItemTemplate>
</ItemsControl>
Replace your code with this
<TabItem Header="Roles" >
<ListBox Margin="10" Width="373" Height="236">
<ListBox.ItemTemplate>
<DataTemplate>
<StackPanel Orientation="Horizontal">
<TextBlock Text="MyText"/>
<CheckBox IsChecked="False"/>
</StackPanel>
</DataTemplate>
</ListBox.ItemTemplate>
<ListBoxItem>Hi</ListBoxItem>
</ListBox>
</TabItem>
and tell us if it still shows blank
Better still, just use the new CheckListBox control in the Extended WPF Toolkit
http://wpftoolkit.codeplex.com/wikipage?title=CheckListBox&referringTitle=Home
This might help
1.Inorder to work datatemplate you must specify itemsource, here i have bounded a Stateslist a collection of items into it.
2.Also set the Datacontext to ViewModel or the CodeBehind as datacontext.
3.Datacontext will distribute the StateList properties collection to the listbox itemsource
using codebehind -
public Window1()
{
InitializeComponent();
this.DataContext = this;
LoadData();
}
using viewmodel
public Window1()
{
InitializeComponent();
DataContext = new Window1ViewModel();
LoadData();
}
//MyItemsource Property for listbox
private ObservableCollection<States> _stateslist;
public ObservableCollection<States> StatesList
{
get { return _stateslist; }
set
{
_stateslist = value;
RaisePropertyChanged(() => StatesList);
}
}
// Sample Data Loading
public void LoadData()
{
StatesList = new ObservableCollection<States>();
StatesList.Add(new States
{
StateName = "Kerala"
});
StatesList.Add(new States
{
StateName = "Karnataka"
});
StatesList.Add(new States
{
StateName = "Goa"
});
}
Window1.Xaml
<ListBox ItemsSource="{Binding StatesList}" >
<ListBox.ItemTemplate>
<DataTemplate>
<StackPanel>
<CheckBox IsChecked="{Binding IsSelected"} Content="{Binding StateName}" />
<TextBox Text="{Binding TextBoxValue}" />
</StackPanel>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
Check this out it isworking..you are using TabItem but you didnt define it in TabControl
<TabControl>
<TabItem Header="Tab1">
<ListBox Margin="10" Width="373" Height="236">
<ListBox.Items>
<StackPanel Orientation="Horizontal">
<TextBlock Text="MyText"/>
<CheckBox IsChecked="False"/>
</StackPanel>
</ListBox.Items>
</ListBox>
</TabItem>
</TabControl>
If you are new in WPF use XamlPadX it will give you great help to practice out on it..