Data Will Not Bind WP - c#

Im trying to bind data from a XML file, ive followed tuts from mdsn and other online sources but i keep getting an error, if i bind the data to a listbox it works fine.
public void LoadPage()
{
XDocument loadedData = XDocument.Load("page01.xml");
var data = from query in loadedData.Descendants("page")
select new PageReader
{
PageNumber = (int)query.Element("pnumber"),
ChapterTitle = (string)query.Element("ctitle"),
ChapterNumber = (int)query.Element("cnumber")
};
LayoutRoot.DataContext = data;
}
and the XAML
Grid x:Name="LayoutRoot" Background="#FFFFFEFE">
<StackPanel>
<Grid>
<Rectangle Fill="#FF424242" HorizontalAlignment="Left" Height="60" Stroke="Black" VerticalAlignment="Top" Width="480"/>
<StackPanel Orientation="Horizontal">
<TextBlock Width="100" TextWrapping="Wrap" MaxWidth="100" MaxHeight="58" TextAlignment="Center" HorizontalAlignment="Center" VerticalAlignment="Center" Foreground="#FFB6AEAE" FontFamily="{StaticResource lob2}" Text="{Binding ChapterNumber}"/>
<TextBlock Width="280" TextWrapping="Wrap" MaxWidth="300" MaxHeight="58" TextAlignment="Center" HorizontalAlignment="Center" VerticalAlignment="Center" Foreground="#FFB6AEAE" FontFamily="{StaticResource lob2}" Text="{Binding ChapterTitle}"/>
<TextBlock Width="100" TextWrapping="Wrap" MaxWidth="100" MaxHeight="58" TextAlignment="Center" HorizontalAlignment="Center" VerticalAlignment="Center" Foreground="#FFB6AEAE" FontFamily="{StaticResource lob2}" Text="{Binding PageNumber}"/>
</StackPanel>
</Grid>
<Grid Height="30"></Grid>
<TextBlock x:Name="PageText" Height="640" ScrollViewer.VerticalScrollBarVisibility="Visible"></TextBlock>
</StackPanel>
</Grid>

Your data is of type IEnumerable<PageReader>, which is why it would work with a ListBox as ListBox is expecting a collection.
If you change
LayoutRoot.DataContext = data;
to
LayoutRoot.DataContext = data.FirstOrDefault();
At least you should see some data show up on the UI.

Related

How to access a specific item in itemscontrol and retrieve some data in UWP

I have an ItemsControl with DataTemplate in my Page.Xaml and the code is like below:
<ItemsControl x:Name="chatUI" VerticalAlignment="Bottom">
<ItemsControl.ItemTemplate>
<DataTemplate>
<Grid x:Name="myGrid" Width="340" Background="{Binding Background}" HorizontalAlignment="{Binding GridHorizontalAlign}" Margin="10,0,10,10" MinHeight="45" BorderBrush="#FF003A4F" BorderThickness="0,0,0,2">
<Polygon Visibility="{Binding RightVisibility}" Fill="{Binding Background}" Points="0,0 5,6, 0,12" VerticalAlignment="Top" HorizontalAlignment="Right" Margin="0,0,-5,0" />
<Polygon Visibility="{Binding LeftVisibility}" Fill="{Binding Background}" Points="5,0 0,6, 5,12" VerticalAlignment="Top" HorizontalAlignment="Left" Margin="-5,0,0,0" />
<Grid>
<Grid.RowDefinitions>
<RowDefinition />
<RowDefinition />
</Grid.RowDefinitions>
<TextBlock Text="{Binding Text}" TextWrapping="Wrap" FontSize="15" FontFamily="Segoe UI" Foreground="White" Margin="10,10,10,0"/>
<TextBlock Grid.Row="1" Text="{Binding Time}" TextWrapping="Wrap" FontSize="11" FontFamily="Segoe UI" Foreground="LightGray" Margin="10,0,10,5" VerticalAlignment="Bottom" TextAlignment="Right"/>
</Grid>
</Grid>
</DataTemplate>
</ItemsControl.ItemTemplate>
</ItemsControl>
What I need right now is getting Text which is bound to the TextBlock when I right click on the grid named myGrid. How is that possible in C#?
We can add the RightTapped event of the Grid, it will be fired when you right click the Grid.
In the RightTapped event we can use Grid.Children to get the collection of child elements of the Grid. That we can get the Grid in the root Grid that named myGrid. That we can use the Grid.Children to get the TextBlock in the Grid.
For example:
private async void myGrid_RightTapped(object sender, RightTappedRoutedEventArgs e)
{
var RightTapGrid = sender as Grid;
var childernElements = RightTapGrid.Children;
foreach (var item in childernElements)
{
var grid = item as Grid;
if (grid != null)
{
var itemchildernElements = grid.Children;
foreach (var text in itemchildernElements)
{
var textBlock = text as TextBlock;
var dialog = new ContentDialog()
{
Title = textBlock.Text,
MaxWidth = this.ActualWidth
};
dialog.PrimaryButtonText = "OK";
dialog.SecondaryButtonText = "Cancel";
await dialog.ShowAsync();
break;
}
}
}
}
If you get your Binding Data from Class called ClassName
You can try this code
XAML:
<ListView x:Name="chatUI" VerticalAlignment="Bottom" SelectionChanged="chatUI_SelectionChanged">
<ListView.ItemTemplate>
<DataTemplate>
<Grid x:Name="myGrid" Width="340" Background="{Binding Background}" HorizontalAlignment="{Binding GridHorizontalAlign}" Margin="10,0,10,10" MinHeight="45" BorderBrush="#FF003A4F" BorderThickness="0,0,0,2">
<Polygon Visibility="{Binding RightVisibility}" Fill="{Binding Background}" Points="0,0 5,6, 0,12" VerticalAlignment="Top" HorizontalAlignment="Right" Margin="0,0,-5,0" />
<Polygon Visibility="{Binding LeftVisibility}" Fill="{Binding Background}" Points="5,0 0,6, 5,12" VerticalAlignment="Top" HorizontalAlignment="Left" Margin="-5,0,0,0" />
<Grid>
<Grid.RowDefinitions>
<RowDefinition />
<RowDefinition />
</Grid.RowDefinitions>
<TextBlock Text="{Binding Text}" TextWrapping="Wrap" FontSize="15" FontFamily="Segoe UI" Foreground="White" Margin="10,10,10,0"/>
<TextBlock Grid.Row="1" Text="{Binding Time}" TextWrapping="Wrap" FontSize="11" FontFamily="Segoe UI" Foreground="LightGray" Margin="10,0,10,5" VerticalAlignment="Bottom" TextAlignment="Right"/>
</Grid>
</Grid>
</DataTemplate>
</Listview.ItemTemplate>
And add SelectionChanged Event :
private void chatUI_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
ListView view = (ListView)sender;
//Get Selected Item
ClassName class = view.SelectedItem as ClassName;
string path = class.Text;
// Now we have Text of selected item in Listview
}

How to create databinding in code behind using the same object that is initiated in xaml?

I have the following code :
<Window x:Class="WpfApplication3.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:local="clr-namespace:WpfApplication3" xmlns:oxy="http://oxyplot.org/wpf"
xmlns:vm="clr-namespace:ViewModel;assembly=ViewModel"
Background="#FFDEDEDE"
WindowStyle="None"
AllowsTransparency="True"
WindowStartupLocation="CenterScreen"
mc:Ignorable="d"
Title="Compression Test" Height="1080" Width="1920">
<Window.Resources>
<vm:MainViewModel x:Key="vmMain"
sampleCount="100" />
</Window.Resources>
<Grid x:Name="gridUI">
<StackPanel Orientation="Vertical">
<StackPanel Height="100">
<Border Background="#FF8986D3" Height="100" Margin="0,0,0,30" >
<TextBlock Text="COMPRESSION TEST" FontFamily="Sans-serif" FontSize="30" Foreground="#FFF9F9F9" VerticalAlignment="Center" FontWeight="Medium" HorizontalAlignment="Center"/>
</Border>
</StackPanel>
<StackPanel Orientation="Horizontal" Height="auto">
<Border BorderBrush="White" BorderThickness="2" >
<StackPanel Orientation="Vertical" Width="200" Height="1080">
<Label FontSize="24" FontFamily="Sans-serif" FontWeight="Medium" Name="doc" Foreground="White" Background="#FFA39AD8" Width="200" HorizontalContentAlignment="Center" Height="43">Files</Label>
<Border BorderBrush="#FFD4D4D4" BorderThickness="0.5" Grid.Row="3"></Border>
<StackPanel Name="sp_doc" Margin="0,10,0,0" >
<StackPanel Orientation="Horizontal" Name="sp_sample_button" Grid.Row="0" Grid.Column="0">
<Image Source="pack://application:,,,/Resources/413.png" Height="40" Width="40" UseLayoutRounding="True" MouseDown="sampleDropDown" Cursor="Hand" Margin="5,0,0,0" Name="up_arrow"/>
<Image Source="pack://application:,,,/Resources/412.png" Height="40" Width="40" UseLayoutRounding="True" MouseDown="sampleDropDown" Cursor="Hand" Margin="5,0,0,0" Name="down_arrow" Visibility="Collapsed"/>
<!--<Button x:Name="sss" Click="sampleDropDown">s</Button>-->
<Label FontSize="18" FontFamily="Sans-serif" FontWeight="Light" Name="sam" Foreground="White" Margin="10">Samples</Label>
</StackPanel>
<StackPanel Orientation="Vertical" Name="sp_s">
</StackPanel>
<StackPanel Orientation="Horizontal" Grid.Column="1" Grid.Row="1">
<Image Source="pack://application:,,,/Resources/413.png" Height="40" Width="40" UseLayoutRounding="True" RenderTransformOrigin="-0.,0.558" MouseDown="reportDropDown" Cursor="Hand" Margin="5,0,0,0" Name="up_arrow1"/>
<Image Source="pack://application:,,,/Resources/412.png" Height="40" Width="40" UseLayoutRounding="True" Cursor="Hand" Margin="5,0,0,0" Name="down_arrow1" Visibility="Collapsed" MouseDown="reportDropDown"/>
<!--<Button Click="reportDropDown">r</Button>-->
<Label FontFamily="Sans-serif" FontWeight="Light" Foreground="White" FontSize="18" Margin="10">Reports</Label>
</StackPanel>
<StackPanel Orientation="Vertical" Name="sp_r">
</StackPanel>
</StackPanel>
</StackPanel>
</Border>
<StackPanel Width="1781">
<StackPanel Orientation="Horizontal" Background="#FFFDFDFD" Height="111">
<TextBox Name="sampleCount" Text="{Binding sampleCount, Source={StaticResource vmMain}, UpdateSourceTrigger=PropertyChanged}" Width="200"></TextBox>
<Button Cursor="Hand" Height="75" Width="75" Style="{StaticResource CircleButton}" FontFamily="Sans-Serif" FontSize="25" Foreground="White" Click="NewSample_Click" Content="+" Margin="20,0,0,0" Background="#FFACAABF" />
<StackPanel Margin="20,19,0,0">
<Image Source="pack://application:,,,/Resources/file512.png" Height="75" Width="75" UseLayoutRounding="True" Margin="0,0,0,0" MouseDown="CreateReport_Click" Cursor="Hand" SnapsToDevicePixels="True"/>
</StackPanel>
<Image Source="pack://application:,,,/Resources/play1.png" Height="75" Width="75" UseLayoutRounding="True" Margin="20,18,0,18" MouseDown="CreateReport_Click" Cursor="Hand" SnapsToDevicePixels="True"/>
<Image Source="pack://application:,,,/Resources/1131.png" Height="75" Width="75" UseLayoutRounding="True" Margin="1340,0,0,0" MouseDown="CreateReport_Click" Cursor="Hand"/>
</StackPanel>
<Frame x:Name="newSampleFrame" Content="" HorizontalAlignment="center" VerticalAlignment="center" Width="934" Height="456" NavigationUIVisibility="Hidden" RenderTransformOrigin="0.408,0.5" Visibility="Collapsed"/>
<Frame x:Name="reportFrame" Content="" HorizontalAlignment="Center" Height="842" VerticalAlignment="Center" Width="595" Margin="0,100,0,0" NavigationUIVisibility="Hidden"/>
<Frame x:Name="graphFrame" Content="" HorizontalAlignment="Center" Height="456" VerticalAlignment="Center" Width="934" NavigationUIVisibility="Hidden" Visibility="Collapsed"/>
</StackPanel>
</StackPanel>
</StackPanel>
</Grid>
</Window>
MainViewModel.cs :
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ViewModel
{
public class MainViewModel : ObservableObject
{
public MainViewModel()
{
}
private string[] sampleName;
private string _sampleCount;
public Data obj2 = new Data();
public string this[int pos]
{
get
{
return sampleName[pos];
}
set
{
sampleName[pos] = value;
}
}
public string sampleCount
{
get
{
return _sampleCount;
}
set
{
if (value != _sampleCount)
{
_sampleCount = value;
OnPropertyChanged("sampleCount");
Console.WriteLine("Test");
Console.WriteLine(value);
obj2.sampleCount = value;
SaveFile.saveFileMain(obj2);
}
}
}
}
}
And I have the following code that create a textblock whenever I click on the OK button :
window2.xaml.cs:
private void Ok_Click(object sender, MouseButtonEventArgs e)
{
MainWindow win = (MainWindow)Application.Current.MainWindow;
int i = 1; // counter for the name of each new textblock
string name = String.Concat("sample", i);
// add textblok to the document list of new samples
if (File_name.Text != "")
{
TextBlock sampleText = new TextBlock();
sampleText.Text = File_name.Text;
sampleText.FontSize = 14;
sampleText.FontFamily = new FontFamily("Sans-serif");
sampleText.FontWeight = FontWeights.DemiBold;
sampleText.Margin = new Thickness(20,0,0,0);
sampleText.Name = name;
sampleText.PreviewMouseDown += new MouseButtonEventHandler(test1);
sampleText.Visibility = System.Windows.Visibility.Collapsed;
//binding
Binding myBinding = new Binding();
myBinding.Source =
myBinding.Path = new PropertyPath("sampleName");
myBinding.Mode = BindingMode.TwoWay;
myBinding.UpdateSourceTrigger = UpdateSourceTrigger.PropertyChanged;
sampleText.SetBinding(TextBlock.TextProperty, myBinding);
Grid.SetColumn(sampleText, 0);
win.sp_s.Children.Add(sampleText);
// checking if the drop down of sample is already open, if so it will show the last textblock with pressing the arrow button.
var textblockSample = win.sp_s.Children.OfType<TextBlock>().FirstOrDefault();
if (textblockSample.Visibility == System.Windows.Visibility.Visible)
{
sampleText.Visibility = System.Windows.Visibility.Visible;
}
}
i += 1; // increasing the loop of names by 1
this.Close();
}
Is it possible to use the same object that is initiated in xaml (vmMain) as a source for binding the textblock (sample text) to sampleName property?
Not sure why you don't set DataContext of your MainWindow to MainViewModel.
<Window.DataContext>
<StaticResourceExtension ResourceKey="vmMain" />
</Window.DataContext>
Or, you can even set DataContext via MainWindow's code behind, which you don't seem to intent to not keep it untouched.
Then to set binding source:
myBinding.Source = this.DataContext;
In the case you refused to set the DataContext, you still can:
myBinding.Source = this.FindResource("vmMain") as MainViewModel;
Not sure if I managed to solve your problem.
Edit
I just realised your binding is in window2. You should do this:
myBinding.Source = win.DataContext;
Similarly, myBinding.Source = this.FindResource("vmMain") as MainViewModel; should also be changed to myBinding.Source = win.FindResource("vmMain") as MainViewModel;.
This is provided you still have that MainWindow win = (MainWindow)Application.Current.MainWindow; line there.
I believe that what you are looking for is the resources property:
myBinding.Source = Resources["vmMain"];
Resource allows you to access the XAML-defined (or otherwise) resources for the current object - the window.
You can also access the resources of any FrameworkElement in the same manner.
EDIT: I hadn't noted the fact that the vmMain was in a different class. With this in mind, no there is no way to reference that object directly from Window2 as there may be multiple MainWindows so you'd have to pick which MainWindow instance the vmMain should be taken from.
What you can do, however is create vmMain in your Application object (App.xaml). This would then share that object across all FrameworkElements in your application. To access this you could use
myBinding.Source = Application.Currennt.Resources["vmMain"];

How to display image to my listbox from my database

The property in the database is image. What's in the content is binary data. This is the datatemplate of the listbox:
<DataTemplate x:Key="ItemTemplate">
<Grid Width="467" Height="123" Margin="5,0,0,0">
<Image Name="imgProduct" Source="{Binding pImage}" HorizontalAlignment="Left" Margin="0,5" Width="115"/>
<TextBlock Text="{Binding pName}" Margin="120,0,133,92" Foreground="Black" FontFamily="Tahoma" FontSize="22.667"/>
<TextBlock Text="{Binding pPrice}" Margin="146,69,263,35" Foreground="Black" FontSize="13.333"/>
<TextBlock Text="{Binding pQty}" Margin="232,30,183,76" Foreground="#FF11BB00" FontSize="13.333" FontFamily="Tahoma"/>
<TextBlock Text="{Binding pRewardCost}" Margin="433,89,0,14" FontSize="13.333" Foreground="#7F000000"/>
<TextBlock Text="{Binding pSalesPrice}" Margin="155,85,233,14" Foreground="#FF005910" FontSize="17.333" RenderTransformOrigin="-0.196,0.375"/>
<TextBlock HorizontalAlignment="Left" Margin="120,31,0,0" TextWrapping="Wrap" VerticalAlignment="Top" FontSize="13.333" Height="15" Width="114">
<Run Text="Quantity Available:"/>
<LineBreak/>
<Run Text=":"/>
</TextBlock>
<TextBlock HorizontalAlignment="Left" Margin="120,69,0,0" TextWrapping="Wrap" Text="SGD" VerticalAlignment="Top" FontSize="13.333" RenderTransformOrigin="-1.923,0.625" Foreground="Black"/>
<TextBlock HorizontalAlignment="Left" Margin="120,85,0,0" TextWrapping="Wrap" Text="SGD" VerticalAlignment="Top" FontSize="17.333" RenderTransformOrigin="-1.923,0.625"/>
<TextBlock HorizontalAlignment="Left" Margin="318,89,0,0" TextWrapping="Wrap" Text="Reward Points cost:" VerticalAlignment="Top" FontSize="13.333" Foreground="#7F000000"/>
<InkPresenter HorizontalAlignment="Left" Height="2" Margin="122,75,0,0" VerticalAlignment="Top" Width="74" Background="Black" RenderTransformOrigin="0.5,0.5">
<InkPresenter.RenderTransform>
<CompositeTransform ScaleY="-1"/>
</InkPresenter.RenderTransform>
</InkPresenter>
<InkPresenter HorizontalAlignment="Left" Height="2" Margin="0,117,0,0" VerticalAlignment="Top" Width="467" Background="#66000000"/>
</Grid>
</DataTemplate>
The C# Code that consumes the database and shows as items on the listbox is as below:
protected override void OnNavigatedTo(System.Windows.Navigation.NavigationEventArgs e)
{
var pdtQry = from pdt in fypDB.Products
select pdt;
productCollection = new DataServiceCollection<Product>();
productCollection.LoadCompleted += new
EventHandler<LoadCompletedEventArgs>(productCollection_LoadCompleted);
productCollection.LoadAsync(pdtQry);
}
void productCollection_LoadCompleted(Object sender, LoadCompletedEventArgs e)
{
if (productCollection.Continuation != null) productCollection.LoadNextPartialSetAsync();
else
{
listboxSearch.ItemsSource = productCollection;
}
}
After debugging, pName, pPrice, pQty, pRewardCost, and pSalesPrice. However the image is not displayed. I think it may be because the image is not of the same format. The format in dbo is image and is <binary data>. Is there any way to convert and display it? Thanks in advance!!

Delete selected item from listbox in windowsphone using c#

i want delete selected item from my listbox using context menu drop-down box here is my xaml
<ListBox Margin="3,60,1,10" Grid.Row="1" Name="lstNews" Tap="lstNews_Tap" Width="476" d:LayoutOverrides="VerticalMargin">
<ListBox.ItemTemplate>
<DataTemplate>
<StackPanel Grid.Row="1" Orientation="Horizontal" Height="120" Width="478">
<StackPanel.Background>
<ImageBrush ImageSource="Images/Text-ALU.png" Stretch="Fill" />
</StackPanel.Background>
<toolkit:ContextMenuService.ContextMenu>
<toolkit:ContextMenu>
<toolkit:MenuItem Header="Delete" Click="MenuItem_Click"/>
<toolkit:MenuItem Header="Open" Click="MenuItem_Click"/>
</toolkit:ContextMenu>
</toolkit:ContextMenuService.ContextMenu>
<Grid HorizontalAlignment="Left" Width="30" Background="#FF0195D5" Margin="0,0,0,2" Height="118">
<TextBlock x:Name="txtDate" TextWrapping="Wrap" Text="{Binding Path=newsDate}" RenderTransformOrigin="0.5,0.5" Margin="-43.169,44.001,-43.831,0" UseLayoutRounding="False" d:LayoutRounding="Auto" TextAlignment="Center" Height="30" VerticalAlignment="Top" Width="117">
<TextBlock.RenderTransform>
<CompositeTransform Rotation="-90"/>
</TextBlock.RenderTransform>
</TextBlock>
</Grid>
<Grid HorizontalAlignment="Left" Width="5" Height="120"/>
<StackPanel Orientation="Vertical" VerticalAlignment="Top" Width="432" Height="114">
<TextBlock x:Name="txtTitle" Height="27" TextWrapping="Wrap" Text="{Binding Path=newsTitle}" Foreground="Black" FontSize="18.667" HorizontalAlignment="Left" Width="432" FontWeight="Bold" />
<StackPanel Orientation="Horizontal" Width="432" Height="27">
<TextBlock x:Name="txtBy" Height="27" TextWrapping="Wrap" Text="{Binding Path=newsSource}" Foreground="Black" FontSize="18.667" Width="399"/>
<Image x:Name="imgArrow" Width="25" Source="Images/Go-In-Arrow.png" Height="25" Margin="5,0,0,0"/>
</StackPanel>
<StackPanel Orientation="Horizontal" Width="433" Height="60">
<TextBlock x:Name="txtDesc" Height="58" TextWrapping="Wrap" Foreground="Black" Text="{Binding Path=newsShortDescription}" FontSize="18.667" Width="371"/>
<TextBlock x:Name="txtID" Height="56" Text="{Binding Path=newsID}" TextWrapping="Wrap" Foreground="Black" FontSize="18.667" Width="8" Visibility="Collapsed"/>
<Image x:Name="imgType" Width="35" Source="{Binding Path=newsTypeImage}" Height="40" Margin="27,20,0,0" d:LayoutOverrides="Height"/>
</StackPanel>
</StackPanel>
</StackPanel>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
here is what i am trying to do on delete event "MenuItem_Click" but than it throws error "Operation not supported on read-only collection.so what is code to delete selected item on that click event
// this is code to delete i am trying--> lstNews.Items.Remove(lstNews.SelectedItem.ToString());
//below is code im trying to set listboxitemsource
private void FillListBox()
{
fulllist = new nList();
lstNews.ItemsSource = fulllist;
}
public class nList : List<NewsData>
{
StringData sd = new StringData();
public IList<NewsData> GetLCList()
{
IList<NewsData> lcList = null;
using (NewsDataContext context = new NewsDataContext(sd.news_string))
{
IQueryable<NewsData> query = (from app in context.NewsData select app).OrderByDescending(app => app.entryID);
lcList = query.ToList();
}
return lcList;
}
public nList()
{
IList<NewsData> lcData = this.GetLCList();
StringBuilder messageBuilder = new StringBuilder();
foreach (NewsData lc in lcData)
{
Add(new NewsData
{
newsID = lc.newsID,
newsTitle = lc.newsTitle,
newsSource = lc.newsSource,
newsDate = (new GetDate()).getdate(lc.newsDate),//(new AnnouncementList()).getdate(lc.newsDate),
newsShortDescription = lc.newsShortDescription,
newsTypeImage = lc.newsTypeImage,
newsSharing = lc.newsSharing
});
}
}
}
lstNews.Items is list of object that are displayed on the page. So this lstNews.Items is collection of your datatemplate so that is why when you tried lstNews.Items.Remove(lstNews.SelectedItem.ToString()) than this fails.
you should use lstNews.Items.Remove(lstNews.SelectedItem) to delete item.
But for best practice it is prefered to delete item from the source not from the list. i.e. You should delete item from fulllist and reassign it as lstNews.ItemsSource = fulllist;
Changes done in your code
fulllist should be a type of ObservableCollection so that all the changes done on data can be reflected to UI.
To convert List to ObservableCollection Following code can be used:
fulllist = new ObservableCollection<NewsData>(new nList());
Add the implementation for deleting data from fulllist a possible implementation could be:
object obj = lstNews.SelectedItem;
if(obj is NewsData){
fulllist.Remove((NewsData)obj);
lstNews.ItemsSource = fulllist;
}

My button doesn't work inside a method

I have a xaml page with a reaction form. I load this reaction dynamicly in a listbox but the button that I use on this reaction doesn't work. I load the reactions as objects in the listbox.
This is the reaction
<Grid x:Name="LayoutRoot" VerticalAlignment="Stretch">
<Border Background="DarkGray" CornerRadius="10" Width="400">
<StackPanel Orientation="Vertical" Width="400" Background="DarkGray" Margin="10,10,10,10">
<Grid>
<TextBlock HorizontalAlignment="Left" Name="tbDateCreated" Text="tbDateCreated" VerticalAlignment="Stretch" FontSize="15" TextWrapping="NoWrap" FontFamily="Segoe WP" Width="152" TextAlignment="Left" Foreground="White" Margin="190,0,0,0" />
<TextBlock HorizontalAlignment="Left" Name="tbTimeCreated" Text="tbTimeCreated" VerticalAlignment="Stretch" FontSize="15" TextWrapping="NoWrap" FontFamily="Segoe WP" Width="152" TextAlignment="Left" Foreground="White" Margin="270,0,-70,0" />
<TextBlock HorizontalAlignment="Left" Name="tbAuthor" Text="tbAuthor" VerticalAlignment="Stretch" FontSize="15" TextWrapping="NoWrap" FontFamily="Segoe WP" FontWeight="Bold" TextAlignment="Left" Margin="10,0,0,0" Width="158" Foreground="White" />
</Grid>
<TextBlock HorizontalAlignment="Stretch" Name="tbContent" Text="tbContent" VerticalAlignment="Stretch" FontSize="15" TextWrapping="Wrap" FontFamily="Segoe WP" TextAlignment="Left" Margin="10,5,20,0" Foreground="White" />
<Line Stretch="Fill" Stroke="Black" X1="0" X2="1" Y1="0" Y2="0" Margin="10,20,10,0" />
<Border Background="Gray" Width="90" Height="30" Margin="-290,10,0,0" CornerRadius="10">
<Button x:Name="reageer" BorderBrush="Gray" Background="Gray" Margin="-5,-12,0,0" Height="60" Width="100" FontSize="12" Click="Button_Click" Tap="reageer_Tap" Content="Reageer" VerticalContentAlignment="Top"/>
</Border>
</StackPanel>
</Border>
</Grid>
And this is the code to load the reaction with data.
public string DateCreated { get { return tbDateCreated.Text; } set { tbDateCreated.Text = value; } }
public string TimeCreated { get { return tbTimeCreated.Text; } set { tbTimeCreated.Text = value; } }
public string Author { get { return tbAuthor.Text; } set { tbAuthor.Text = value; } }
public string TextContent { get { return tbContent.Text; } set { tbContent.Text = value; } }
In the next page I load this reaction.
<ListBox Margin="0,0,0,20" Name="lbComments" VerticalAlignment="Top" IsHitTestVisible="False"/>
How can I use the button in my reaction to work on the page where the listbox is?

Categories