I have a listview whose data is extracted from sqlite database, as shown below:
I want to check the user click the delete button, then the data on the list is deleted and the data in the sqlite database also deleted.
XAML:
<ListView x:Name="ListTryout" Grid.Row="1" Margin="0,5,0,10" ItemsSource="{Binding Source={StaticResource itemsViewSource}}" DataContext="{Binding SelectedItem, ElementName=itemListView}" IsItemClickEnabled="True" SelectionChanged="ListTryout_SelectionChanged" Background="{x:Null}" SelectionMode="Single">
<ListView.ItemTemplate>
<DataTemplate>
<Grid>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="*"/>
<ColumnDefinition Width="auto"/>
</Grid.ColumnDefinitions>
<StackPanel Grid.Column="0" Orientation="Vertical">
<TextBlock Margin="10,10,0,0" FontSize="20" Text="{Binding Judul}" Style="{StaticResource CaptionTextBlockStyle}" VerticalAlignment="Top" HorizontalAlignment="Left"/>
<TextBlock Margin="10,10,0,0" FontSize="17" Text="{Binding JumlahSoal}" VerticalAlignment="Top" HorizontalAlignment="Left" FontWeight="SemiLight"/>
<TextBlock Margin="10,10,0,0" FontSize="17" Text="{Binding Durasi}" VerticalAlignment="Top" HorizontalAlignment="Left" FontWeight="SemiLight" Visibility="Collapsed"/>
<Line X1="0" X2="1" Stretch="Fill" Margin="10,10,10,0" Stroke="#FF4B4B4B"/>
</StackPanel>
<AppBarButton x:Name="deleteItemBtn" Grid.Column="1" Margin="0,0,50,0" Icon="Delete" HorizontalAlignment="Right" Click="deleteItemBtn_Click"/>
</Grid>
</DataTemplate>
</ListView.ItemTemplate>
</ListView>
Code:
private void ReadTryoutList_Loaded(object sender, RoutedEventArgs e)
{
ReadAllDBName dbName = new ReadAllDBName();
DB_TryoutList = dbName.GetAllDBName();
ListTryout.ItemsSource = DB_TryoutList.OrderByDescending(i => i.ID).ToList();//Binding DB data to LISTBOX and Latest contact ID can Display first.
if(DB_TryoutList.Count == 0)
{
statuskosongStack.Visibility = Visibility.Visible;
ListTryout.Visibility = Visibility.Collapsed;
}
else
{
statuskosongStack.Visibility = Visibility.Collapsed;
ListTryout.Visibility = Visibility.Visible;
}
}
private void deleteItemBtn_Click(object sender, RoutedEventArgs e)
{
Db_Helper.DeleteQuiz(currentquiz.ID);
}
DatabaseHelper class:
public void CreateDatabase(string DB_PATH)
{
if (!CheckFileExists(DB_PATH).Result)
{
using (SQLite.Net.SQLiteConnection conn = new SQLite.Net.SQLiteConnection(new SQLite.Net.Platform.WinRT.SQLitePlatformWinRT(), DB_PATH))
{
conn.CreateTable<DBName>();
}
}
}
private async Task<bool> CheckFileExists(string fileName)
{
try
{
var store = await Windows.Storage.ApplicationData.Current.LocalFolder.GetFileAsync(fileName);
return true;
}
catch
{
return false;
}
}
// Insert the new history in the DBName table.
public void Insert(DBName dBName)
{
using (SQLite.Net.SQLiteConnection conn = new SQLite.Net.SQLiteConnection(new SQLite.Net.Platform.WinRT.SQLitePlatformWinRT(), App.DB_PATH))
{
conn.RunInTransaction(() =>
{
conn.Insert(dBName);
});
}
}
public DBName ReadName(int quizid)
{
using (SQLite.Net.SQLiteConnection conn = new SQLite.Net.SQLiteConnection(new SQLite.Net.Platform.WinRT.SQLitePlatformWinRT(), App.DB_PATH))
{
var existingName = conn.Query<DBName>("select * from DBName where ID =" + quizid).FirstOrDefault();
return existingName;
}
}
public ObservableCollection<DBName> ReadAllDBName()
{
try
{
using (SQLite.Net.SQLiteConnection conn = new SQLite.Net.SQLiteConnection(new SQLite.Net.Platform.WinRT.SQLitePlatformWinRT(), App.DB_PATH))
{
List<DBName> myCollection = conn.Table<DBName>().ToList<DBName>();
ObservableCollection<DBName> DBNameList = new ObservableCollection<DBName>(myCollection);
return DBNameList;
}
}
catch
{
return null;
}
}
public void DeleteQuiz(string ID)
{
using (SQLite.Net.SQLiteConnection conn = new SQLite.Net.SQLiteConnection(new SQLite.Net.Platform.WinRT.SQLitePlatformWinRT(), App.DB_PATH))
{
var existingquiz = conn.Query<DBName>("delete from DBName where ID ='" + ID + "'").FirstOrDefault();
if (existingquiz != null)
{
conn.RunInTransaction(() =>
{
conn.Delete(existingquiz);
});
}
}
}
I tried it, but the data can not be deleted on listview and also on the sqlite database.
How to handle it?
Set or bind the ItemsSource of the ListView to an ObservableCollection<T> and remove the item from this one, e.g.:
private ObservableCollecton<DBName> _source;
private void ReadTryoutList_Loaded(object sender, RoutedEventArgs e)
{
ReadAllDBName dbName = new ReadAllDBName();
DB_TryoutList = dbName.GetAllDBName();
_source = new ObservableCollecton<DBName>(DB_TryoutList.OrderByDescending(i => i.ID).ToList());
ListTryout.ItemsSource = _source;
if (DB_TryoutList.Count == 0)
{
statuskosongStack.Visibility = Visibility.Visible;
ListTryout.Visibility = Visibility.Collapsed;
}
else
{
statuskosongStack.Visibility = Visibility.Collapsed;
ListTryout.Visibility = Visibility.Visible;
}
}
private void deleteItemBtn_Click(object sender, RoutedEventArgs e)
{
var btn = sender as AppBarButton;
var item = btn.DataContext as DBName;
if (item != null)
{
_source.Remove(item);
Db_Helper.DeleteQuiz(currentquiz.ID);
}
}
I assume that GetAllDBName() are returning an IEnumerable<DBName> and that you are displaying DBNames in the ListView.
Related
I"m trying to make a simple GUI through Xamarin, and running into all sorts of issues. This is an experiment so the code is a bit ugly but Basically, I have 2 pages; Main page and settings page. On the main page I want to go off and make a REST call and populate a list(currently hardcoded). Everything was going OK until I decided to do the Rest call as a async task. Now the topLabel wont update, the listview wont either(although if I tap on it it does). and the button wont switch pages. A lot of this is new to me, but it feels like playing whack a mole. I solve 1 thing a 4 more stop working. I'm sure i'm missing some fundamental thing. Any help is greatly appreciated.
the Xaml:
<?xml version="1.0" encoding="utf-8" ?>
<ContentPage xmlns="http://xamarin.com/schemas/2014/forms"
xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
x:Class="TheButton.MainPage">
<StackLayout Spacing="1">
<Label x:Name="topLabel" TextColor="{Binding TopTextColor}" Text="{Binding itsTopText}" BackgroundColor="LightSlateGray" HorizontalTextAlignment="Center"
FontSize="Title" HorizontalOptions ="FillAndExpand" Padding="10,10,30,10" HeightRequest="50"/>
<StackLayout Spacing="5" VerticalOptions="FillAndExpand">
<ListView x:Name="soundsListView" ItemsSource="{Binding itsButtonSounds}" Margin="5"
ItemSelected="OnListViewItemSelected"
ItemTapped="OnListViewItemTapped"
RowHeight="70">
<ListView.ItemTemplate>
<DataTemplate >
<ViewCell >
<Grid BackgroundColor="{Binding LEDColor}" Padding="1">
<Grid.RowDefinitions>
<RowDefinition Height="Auto" />
<RowDefinition Height="*" />
</Grid.RowDefinitions>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="Auto" />
<ColumnDefinition Width="*" />
</Grid.ColumnDefinitions>
<Label VerticalTextAlignment="Center" HorizontalTextAlignment="Start" VerticalOptions="CenterAndExpand" Grid.Column="1" Grid.Row="0"
Text="{Binding Name}" FontSize="Title"
FontAttributes="Bold" />
<Label Grid.ColumnSpan="3"
Grid.Column="2"
Text="{Binding Description}"
VerticalOptions="StartAndExpand" VerticalTextAlignment="Center"/>
</Grid>
</ViewCell>
</DataTemplate>
</ListView.ItemTemplate>
</ListView>
<StackLayout Spacing="5" Orientation="Horizontal" HeightRequest="120" VerticalOptions="Center" HorizontalOptions="Center">
<Button Text="Add Sound" FontSize="45" Clicked="Handle_Clicked" VerticalOptions="Fill" HorizontalOptions="Fill"/>
</StackLayout>
</StackLayout>
</StackLayout>
</ContentPage>
And The mainPage
namespace TheButton
{
public partial class MainPage : ContentPage
{
public string whatever = "[ { \"Name\": \"hello\", \"ImageUrl\": \"./Sounds/hello.mp3\", \"color\": [255,0,255], \"Description\":\"hello!\", \"order\": 1 }]";
public ObservableCollection<ButtonSound> itsButtonSounds { get; private set; }
public ButtonSound tappedItem;
public bool connectedToModule;
public string itsTopText { get; set; }
public Color TopTextColor { get; set; }
public MainPage()
{
BindingContext = this;
InitializeComponent();
connectedToModule = false;
Console.WriteLine("HI!!!!!");
itsButtonSounds = new ObservableCollection<ButtonSound>();
TopTextColor = Color.Red;
itsTopText = "CONNECTING... Please Wait!";
Console.WriteLine("Connection");
Task.Run( connectToModule);
Console.WriteLine("Done Connection");
MessagingCenter.Subscribe<SettingPage, ButtonSound>(this, "Hi", (itsSender, butt) =>
{
Console.WriteLine("HI!!!!!");
if (tappedItem== null)
{
itsButtonSounds.Add(butt);
}
else
{
var index = itsButtonSounds.IndexOf(tappedItem);
itsButtonSounds[index] = butt;
}
});
}
int count = 0;
void Handle_Clicked(object sender, System.EventArgs e)
{
if (connectedToModule ==true)
{
tappedItem = null;
SettingPage comingPage = new SettingPage();
comingPage.SetToButtonSound();
Navigation.PushModalAsync(comingPage);
}
else
{
DisplayAlert("Not Connected!", "Please put Button into Connection mode by holding the options button for 3 seconds", "OK");
}
}
public async Task connectToModule()
{
var client = new RestClient("http://raspberrypi:5000");
var request = new RestRequest("con", Method.GET);
while (true)
{
Console.WriteLine("REST REQUIESSTT");
var response = client.Execute(request);
if (response.StatusCode == System.Net.HttpStatusCode.OK && response.Content == "accept")
{
connectedToModule = true;
Console.WriteLine($"CONNECTED! OMGOMG!{connectedToModule}");
InitButtonSounds();
Console.WriteLine(response.Content);
Console.WriteLine(connectedToModule == true);
break;
}
Thread.Sleep(500);
}
}
public void InitButtonSounds()
{
//string fileName = "TheButton.data.json";
//var backingFile = Path.Combine(System.Environment.GetFolderPath(System.Environment.SpecialFolder.Personal), "data.json");
//Console.WriteLine(backingFile);
//string jsonString = File.ReadAllText(backingFile);
Console.WriteLine("Nonesense! initbuttons!");
TopTextColor = Color.LightCyan;
itsTopText = "Connected To... Button1";
var jsonButtons = JsonConvert.DeserializeObject<List<ButtonSound>>(whatever);
foreach( ButtonSound bs in jsonButtons)
{
bs.LEDColor = Color.FromRgb(bs.color[0], bs.color[1], bs.color[2]);
Console.WriteLine(bs.Name);
itsButtonSounds.Add(bs);
}
itsButtonSounds.Add(new ButtonSound
{
Name = "Hellosss",
Description ="C:/SomePath",
ImageUrl = "THIS IS REDUNDANT",
LEDColor = Color.FromRgb(225,0,0)
});
itsButtonSounds.Add(new ButtonSound
{
Name = "bye",
Description = "C:/SomePath BLah BLah BLah bladsfgdsfsadhfdshfkadshfkldsafhasdklfdshfdklsafjhdslfka fdsf adsf dsaf adsf h Blah",
ImageUrl = "THIS IS REDUNDANT",
LEDColor = Color.FromRgb(12, 233, 31)
});
itsButtonSounds.Add(new ButtonSound
{
Name = "Doot",
Description = "C:/SomePath",
ImageUrl = "THIS IS REDUNDANT",
LEDColor = Color.FromRgb(122, 122, 11)
});
soundsListView.ItemsSource = itsButtonSounds;
}
void OnListViewItemSelected(object sender, SelectedItemChangedEventArgs e)
{
ButtonSound selectedItem = e.SelectedItem as ButtonSound;
}
void OnListViewItemTapped(object sender, ItemTappedEventArgs e)
{
tappedItem = e.Item as ButtonSound;
Console.WriteLine(tappedItem.Name);
SettingPage comingPage = new SettingPage();
comingPage.itsButton = tappedItem;
comingPage.SetToButtonSound();
Navigation.PushModalAsync(comingPage);
}
}
}
This is my code, There is one listbox in right side, the listbox item is added to the another list box item inside the grid. The Grid is added dynamically by using the context menu. Till it is working fine. But now I want to move the whole list not list items, to the grid dynamically at runtime. Please anyone guide me to drag the whole list and placing the whole list to grid at runtime dynamically.
<Grid>
<Grid>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="*" />
<ColumnDefinition Width="Auto" />
</Grid.ColumnDefinitions>
<WrapPanel
x:Name="mainPanel"
Grid.Column="0"
Background="#F0F0F0"
ScrollViewer.VerticalScrollBarVisibility="Auto">
<WrapPanel.ContextMenu>
<ContextMenu>
<MenuItem Click="MenuItem_Click" Header="Add Pabel" />
</ContextMenu>
</WrapPanel.ContextMenu>
</WrapPanel>
<ListBox
Name="memberCollection"
Grid.Column="1"
Width="150"
HorizontalAlignment="Stretch"
VerticalAlignment="Stretch"
PreviewMouseLeftButtonDown="memberCollection_PreviewMouseLeftButtonDown">
<ListBox.ItemTemplate>
<DataTemplate>
<StackPanel>
<Label Name="Name" Content="{Binding Name}" />
</StackPanel>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
</Grid>
</Grid>
Code Behind
ObservableCollection<Member> member = new ObservableCollection<Member>();
public MainWindow()
{
InitializeComponent();
member.Add(new Member { Name = "Karthick", ID = "20011", Address = "10, MainRoad, Chennai" });
member.Add(new Member { Name = "Suresh", ID = "20012", Address = "11, MainRoad, Madurai" });
member.Add(new Member { Name = "Arun", ID = "20013", Address = "12, MainRoad, Selam" });
member.Add(new Member { Name = "Gokul", ID = "20014", Address = "13, MainRoad, Coimbature" });
member.Add(new Member { Name = "Vishnu", ID = "20015", Address = "14, MainRoad, Goa" });
memberCollection.ItemsSource = member;
}
private void MenuItem_Click(object sender, RoutedEventArgs e)
{
Grid panel = new Grid();
panel.MinHeight = 150;
panel.MinWidth = 150;
panel.Height = 150;
panel.Width = 150;
panel.Margin = new Thickness(15,15,0,10);
Grid gridDrop = new Grid()
{
Background = Brushes.White,
HorizontalAlignment = HorizontalAlignment.Stretch,
VerticalAlignment = VerticalAlignment.Stretch
};
gridDrop.Drop += grid_Drop;
var panelTemplate = new DataTemplate();
var stackPanel = new FrameworkElementFactory(typeof(StackPanel));
stackPanel.SetValue(StackPanel.OrientationProperty, Orientation.Vertical);
var name = new FrameworkElementFactory(typeof(Label));
name.SetBinding(Label.ContentProperty, new Binding("Name"));
var id = new FrameworkElementFactory(typeof(Label));
id.SetBinding(Label.ContentProperty, new Binding("ID"));
var address = new FrameworkElementFactory(typeof(Label));
address.SetBinding(Label.ContentProperty, new Binding("Address"));
stackPanel.AppendChild(name);
stackPanel.AppendChild(id);
stackPanel.AppendChild(address);
panelTemplate.VisualTree = stackPanel;
ListBox listBox = new ListBox()
{
AllowDrop = true,
ItemTemplate = panelTemplate
};
gridDrop.Children.Add(listBox);
panel.Children.Add(gridDrop);
mainPanel.Children.Add(panel);
DataContext = new Member();
}
private void memberCollection_PreviewMouseLeftButtonDown(object sender, MouseButtonEventArgs e)
{
object selectedMember = memberCollection.SelectedItem as Member;
if (selectedMember != null)
{
DragDrop.DoDragDrop(memberCollection, selectedMember, DragDropEffects.Move);
}
}
private void grid_Drop(object sender, RoutedEventArgs e)
{
ListBox listContent = e.Source as ListBox;
if (listContent != null)
Console.WriteLine("", Grid.GetColumn(listContent), Grid.GetRow(listContent));
DataObject item = (((DragEventArgs)e).Data) as DataObject;
object Target = ((Grid)(sender)).DataContext;
if (Target != null)
{
object listItem = item.GetData(Target.GetType());
listContent.Items.Add(listItem);
}
}
If you only want to move the whole list and create a tile for each Member, then this is one way to go:
First of all, you should simplify your template and put it in the XAML.
XAML is much more efficient at handling any kind of template than the code behind
For your left mainPanel:
<ItemsControl x:Name="mainPanel" Grid.Column="0" ItemsSource="{Binding}">
<ItemsControl.ItemsPanel>
<ItemsPanelTemplate>
<WrapPanel Background="#F0F0F0" AllowDrop="True" Drop="mainPanel_Drop">
<WrapPanel.ContextMenu>
<ContextMenu>
<MenuItem Click="MenuItem_Click" Header="Add Panel" />
</ContextMenu>
</WrapPanel.ContextMenu>
</WrapPanel>
</ItemsPanelTemplate>
</ItemsControl.ItemsPanel>
<ItemsControl.ItemTemplate>
<DataTemplate>
<StackPanel Orientation="Vertical" Background="White" AllowDrop="True" Margin="15,15,0,10" Width="150" MinWidth="150" Height="150" MinHeight="150">
<Label Content="{Binding Name}"/>
<Label Content="{Binding ID}"/>
<Label Content="{Binding Address}"/>
</StackPanel>
</DataTemplate>
</ItemsControl.ItemTemplate>
</ItemsControl>
And for your list (no much changes)
<ListBox
Name="memberCollection"
Grid.Column="1"
Width="150"
HorizontalAlignment="Stretch"
VerticalAlignment="Stretch"
ItemsSource="{Binding}"
PreviewMouseLeftButtonDown="memberCollection_PreviewMouseLeftButtonDown">
<ListBox.ItemTemplate>
<DataTemplate>
<StackPanel>
<Label Name="memberName" Content="{Binding Name}" />
</StackPanel>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
I added two ObservableCollection to manage the Data
ObservableCollection<Member> member = new ObservableCollection<Member>();
ObservableCollection<Member> mainPanelMembers = new ObservableCollection<Member>();
public MainWindow()
{
InitializeComponent();
member.Add(new Member { Name = "Karthick", ID = "20011", Address = "10, MainRoad, Chennai" });
member.Add(new Member { Name = "Suresh", ID = "20012", Address = "11, MainRoad, Madurai" });
member.Add(new Member { Name = "Arun", ID = "20013", Address = "12, MainRoad, Selam" });
member.Add(new Member { Name = "Gokul", ID = "20014", Address = "13, MainRoad, Coimbature" });
member.Add(new Member { Name = "Vishnu", ID = "20015", Address = "14, MainRoad, Goa" });
memberCollection.DataContext = member;
mainPanel.DataContext = mainPanelMembers;
}
Then, the creation of a new Tile is much much more simplier:
private void MenuItem_Click(object sender, RoutedEventArgs e)
{
mainPanelMembers.Add(new Member());
}
If you want to copy the whole list, then you have to give the whole ObservableCollection to the DragDrop manager:
private void memberCollection_PreviewMouseLeftButtonDown(object sender, MouseButtonEventArgs e)
{
object collectionDataContext = memberCollection.DataContext;
if (collectionDataContext != null)
{
DataObject dragData = new DataObject("DataContext", collectionDataContext);
DragDrop.DoDragDrop(memberCollection, dragData, DragDropEffects.Move);
}
}
And when you drop it, you can simply add the Member one by one. You could also clear the collection before (but I didn't):
private void mainPanel_Drop(object sender, DragEventArgs e)
{
DataObject item = e.Data as DataObject;
object listItem = item.GetData("DataContext") as IEnumerable<Member>;
if (listItem != null)
{
foreach (Member member in (IEnumerable<Member>)listItem)
{
((ObservableCollection<Member>)mainPanel.DataContext).Add(member);
}
}
}
I'm not sure I understood very well what you wanted... I still don't know how you're using the Tile creation.
Let me know if you need to do something different.
I have a textbox ACLBox that I want to display a string upon initialization of the user interface. Upon initializing, the string flashes for a second then disappears. Why?
Here's the xaml code for the textbox:
<Window x:Class="Funnel.ACL"
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:Funnel"
mc:Ignorable="d"
Title="ACL Configuration" Height="300" Width="560" WindowStartupLocation="CenterScreen"
Closing="exitACL"
Background="LightGray" Name="ACLConfiguration">
<Grid>
<DockPanel>
<Grid x:Name="FunnelGrid" DockPanel.Dock="Top" ShowGridLines="False">
<!--Defining Grid-->
<Grid.ColumnDefinitions>
<ColumnDefinition Width="130"/>
<ColumnDefinition Width="40"/>
<ColumnDefinition Width="40"/>
<ColumnDefinition Width="40"/>
<ColumnDefinition Width="40"/>
<ColumnDefinition Width="30"/>
<ColumnDefinition Width="70"/>
<ColumnDefinition Width="75"/>
<ColumnDefinition Width="75"/>
<ColumnDefinition Width="75"/>
</Grid.ColumnDefinitions>
<Grid.RowDefinitions>
<RowDefinition Height="Auto" />
<RowDefinition Height="Auto" />
<RowDefinition Height="Auto" />
<RowDefinition Height="Auto" />
<RowDefinition Height="Auto" />
<RowDefinition Height="Auto" />
<RowDefinition Height="Auto" />
</Grid.RowDefinitions>
<Label x:Name="Config"
Content="ACL CONFIGURATION"
Grid.Row="0"
Grid.Column="0"
Grid.ColumnSpan="9"
HorizontalAlignment="Center"
Foreground="Blue"
FontWeight="Heavy"
FontSize="16">
</Label>
<CheckBox x:Name="aclCheckbox"
FlowDirection="RightToLeft"
Content="ACL ON"
Foreground="Blue"
FontWeight="Heavy"
FontSize="16"
Grid.Row="1"
Grid.Column="0"
Grid.RowSpan="1"
Grid.ColumnSpan="5"
HorizontalAlignment="Center"
Checked="ACL_Check"
Unchecked="ACL_Unchecked"
/>
<Label x:Name="AddIPAddress" Content="Add IP Address" Grid.Row="2" Grid.Column="0" Width="90" Height="30"></Label>
<TextBox x:Name="AddIPTextBox1" Grid.Row="2" Grid.Column="1" Width="35" Height="20" TextChanged="AddIPTextBox1_TextChanged"></TextBox>
<TextBox x:Name="AddIPTextBox2" Grid.Row="2" Grid.Column="2" Width="35" Height="20" TextChanged="AddIPTextBox2_TextChanged"></TextBox>
<TextBox x:Name="AddIPTextBox3" Grid.Row="2" Grid.Column="3" Width="35" Height="20" TextChanged="AddIPTextBox3_TextChanged"></TextBox>
<TextBox x:Name="AddIPTextBox4" Grid.Row="2" Grid.Column="4" Width="35" Height="20" TextChanged="AddIPTextBox4_TextChanged"></TextBox>
<TextBox x:Name="AddErrorBox" Grid.Row="3" Grid.Column="0" Grid.ColumnSpan="2" HorizontalAlignment="Right" BorderThickness="0" Background="LightGray" FontSize="10" Text="{Binding AddErrorText}"/>
<Button x:Name="AddButton" Grid.Row="3" Grid.Column="1" Grid.ColumnSpan="4" HorizontalAlignment="Center" Height="25" Width="50" Click="addClick" FontSize="12" FontWeight="ExtraBold" Background="LightSteelBlue" VerticalAlignment="Top">ADD</Button>
<Label x:Name="DelIPAddress" Content="Remove IP Address" Grid.Row="4" Grid.Column="0" Width="120" Height="30"></Label>
<TextBox x:Name="DeleteIPTextBox1" Grid.Row="4" Grid.Column="1" Width="35" Height="20" TextChanged="DeleteIPTextBox1_TextChanged"></TextBox>
<TextBox x:Name="DeleteIPTextBox2" Grid.Row="4" Grid.Column="2" Width="35" Height="20" TextChanged="DeleteIPTextBox2_TextChanged"></TextBox>
<TextBox x:Name="DeleteIPTextBox3" Grid.Row="4" Grid.Column="3" Width="35" Height="20" TextChanged="DeleteIPTextBox3_TextChanged"></TextBox>
<TextBox x:Name="DeleteIPTextBox4" Grid.Row="4" Grid.Column="4" Width="35" Height="20" TextChanged="DeleteIPTextBox4_TextChanged"></TextBox>
<TextBox x:Name="DelErrorBox" Grid.Row="5" Grid.Column="0" Grid.ColumnSpan="2" HorizontalAlignment="Right" BorderThickness="0" Background="LightGray" FontSize="10" Text="{Binding DelErrorText}"/>
<Button x:Name="DeleteButton" Grid.Row="5" Grid.Column="1" Grid.ColumnSpan="4" HorizontalAlignment="Center" Height="25" Width="50" Click="deleteClick" FontSize="12" FontWeight="ExtraBold" Background="LightSteelBlue" VerticalAlignment="Top">DELETE</Button>
<Button x:Name="DeleteAllButton" Grid.Row="6" Grid.Column="1" Grid.ColumnSpan="4" HorizontalAlignment="Center" Height="25" Width="80" Click="deleteAllClick" FontSize="12" FontWeight="ExtraBold" Background="LightSteelBlue" VerticalAlignment="Top">REMOVE ALL</Button>
<Label x:Name="ACLBoxLabel" Content="Access Control List" Foreground="Blue" Grid.Row="1" Grid.Column="6" Grid.ColumnSpan="3" HorizontalAlignment="Center"></Label>
<TextBox x:Name="ACLBox"
ScrollViewer.HorizontalScrollBarVisibility="Auto"
ScrollViewer.VerticalScrollBarVisibility="Auto"
ScrollViewer.CanContentScroll="True"
Grid.Row="2"
Grid.Column="6"
Grid.RowSpan="4"
Grid.ColumnSpan="4"
HorizontalAlignment="Left"
VerticalAlignment="Center"
Width="220"
Height="150"
FontSize="14"
IsReadOnly="True"
Text="{Binding ACLBoxText}"
TextWrapping="Wrap"
TextAlignment="Center" />
</Grid>
</DockPanel>
</Grid>
Here's the C# code for the string:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;
namespace Funnel
{
/// <summary>
/// Interaction logic for ACL.xaml
/// </summary>
public partial class ACL : Window
{
AclManager _manage = new AclManager();
FileController _controller = new FileController();
string addStr1;
string addStr2;
string addStr3;
string addStr4;
bool addError;
string delStr1;
string delStr2;
string delStr3;
string delStr4;
bool delError;
public string aclText;
public event PropertyChangedEventHandler PropertyChanged;
public ACL()
{
InitializeComponent();
if(FunnelGlobals.accessControlList)
{
aclCheckbox.IsChecked = true;
}
aclText = _manage.getAclList();
}
private void exitACL(object sender,System.ComponentModel.CancelEventArgs e)
{
_controller.writeAclFile();
}
private void ACL_Check(object sender, RoutedEventArgs e)
{
FunnelGlobals.accessControlList = true;
aclText = _manage.getAclList();
}
private void ACL_Unchecked(object sender, RoutedEventArgs e)
{
FunnelGlobals.accessControlList = false;
aclText = _manage.getAclList();
}
private void AddIPTextBox1_TextChanged(object sender, TextChangedEventArgs e)
{
AddErrorBox.Text = "";
AddIPTextBox1.Text = AddIPTextBox1.Text;
addStr1 = AddIPTextBox1.Text;
if(!_manage.isDigit(addStr1))
{
Color foreColor = (Color)new ColorConverter().ConvertFrom("red");
Brush errBrush = new SolidColorBrush(foreColor);
AddErrorBox.Foreground = errBrush;
AddErrorBox.Text = "Character NOT Valid";
addError = true;
}
else
{
addError = false;
}
ACLBox.Text = _manage.getAclList();
}
private void AddIPTextBox2_TextChanged(object sender, TextChangedEventArgs e)
{
AddErrorBox.Text = "";
AddIPTextBox2.Text = AddIPTextBox2.Text;
addStr2 = AddIPTextBox2.Text;
if (!_manage.isDigit(addStr2))
{
Color foreColor = (Color)new ColorConverter().ConvertFrom("red");
Brush errBrush = new SolidColorBrush(foreColor);
AddErrorBox.Foreground = errBrush;
AddErrorBox.Text = "Character NOT Valid";
}
aclText = _manage.getAclList();
}
private void AddIPTextBox3_TextChanged(object sender, TextChangedEventArgs e)
{
AddErrorBox.Text = "";
AddIPTextBox3.Text = AddIPTextBox3.Text;
addStr3 = AddIPTextBox3.Text;
if (!_manage.isDigit(addStr3))
{
Color foreColor = (Color)new ColorConverter().ConvertFrom("red");
Brush errBrush = new SolidColorBrush(foreColor);
AddErrorBox.Foreground = errBrush;
AddErrorBox.Text = "Character NOT Valid";
}
aclText = _manage.getAclList();
}
private void AddIPTextBox4_TextChanged(object sender, TextChangedEventArgs e)
{
AddErrorBox.Text = "";
AddIPTextBox4.Text = AddIPTextBox4.Text;
addStr4 = AddIPTextBox4.Text;
if (!_manage.isDigit(addStr4))
{
Color foreColor = (Color)new ColorConverter().ConvertFrom("red");
Brush errBrush = new SolidColorBrush(foreColor);
AddErrorBox.Foreground = errBrush;
AddErrorBox.Text = "Character NOT Valid";
}
aclText = _manage.getAclList();
}
private void addClick(object sender, RoutedEventArgs e)
{
String addStr = addStr1 + "." + addStr2 + "." + addStr3 + "." + addStr4;
if(_manage.isLegit(addStr))
{
FunnelGlobals.aclIPs.Add(addStr);
}
if(addError)
{
Color foreColor = (Color)new ColorConverter().ConvertFrom("red");
Brush errBrush = new SolidColorBrush(foreColor);
AddErrorBox.Foreground = errBrush;
AddErrorBox.Text = "Fix Invalid Characters before Adding";
}
else
{
aclText = _manage.getAclList();
}
}
private void DeleteIPTextBox1_TextChanged(object sender, TextChangedEventArgs e)
{
DelErrorBox.Text = "";
DeleteIPTextBox1.Text = DeleteIPTextBox1.Text;
delStr1 = DeleteIPTextBox1.Text;
if (!_manage.isDigit(delStr1))
{
Color foreColor = (Color)new ColorConverter().ConvertFrom("red");
Brush errBrush = new SolidColorBrush(foreColor);
DelErrorBox.Foreground = errBrush;
DelErrorBox.Text = "Character NOT Valid";
delError = true;
}
else
{
delError = false;
}
}
private void DeleteIPTextBox2_TextChanged(object sender, TextChangedEventArgs e)
{
DelErrorBox.Text = "";
DeleteIPTextBox2.Text = DeleteIPTextBox2.Text;
delStr2 = DeleteIPTextBox2.Text;
if (!_manage.isDigit(delStr2))
{
Color foreColor = (Color)new ColorConverter().ConvertFrom("red");
Brush errBrush = new SolidColorBrush(foreColor);
DelErrorBox.Foreground = errBrush;
DelErrorBox.Text = "Character NOT Valid";
delError = true;
}
else
{
delError = false;
}
}
private void DeleteIPTextBox3_TextChanged(object sender, TextChangedEventArgs e)
{
DelErrorBox.Text = "";
DeleteIPTextBox3.Text = DeleteIPTextBox3.Text;
delStr3 = DeleteIPTextBox3.Text;
if (!_manage.isDigit(delStr3))
{
Color foreColor = (Color)new ColorConverter().ConvertFrom("red");
Brush errBrush = new SolidColorBrush(foreColor);
DelErrorBox.Foreground = errBrush;
DelErrorBox.Text = "Character NOT Valid";
delError = true;
}
else
{
delError = false;
}
}
private void DeleteIPTextBox4_TextChanged(object sender, TextChangedEventArgs e)
{
DelErrorBox.Text = "";
DeleteIPTextBox4.Text = DeleteIPTextBox4.Text;
delStr4 = DeleteIPTextBox4.Text;
if (!_manage.isDigit(delStr4))
{
Color foreColor = (Color)new ColorConverter().ConvertFrom("red");
Brush errBrush = new SolidColorBrush(foreColor);
DelErrorBox.Foreground = errBrush;
DelErrorBox.Text = "Character NOT Valid";
delError = true;
}
else
{
delError = false;
}
}
private void deleteClick(object sender, RoutedEventArgs e)
{
String delStr = delStr1 + "." + delStr2 + "." + delStr3 + "." + delStr4;
FunnelGlobals.aclIPs.Remove(delStr);
if (delError)
{
Color foreColor = (Color)new ColorConverter().ConvertFrom("red");
Brush errBrush = new SolidColorBrush(foreColor);
DelErrorBox.Foreground = errBrush;
DelErrorBox.Text = "Fix Invalid Characters before Removing";
}
else
{
aclText = _manage.getAclList();
}
}
private void deleteAllClick(object sender, RoutedEventArgs e)
{
FunnelGlobals.aclIPs.Clear();
aclText = _manage.getAclList();
}
private void ACLBox_Loaded(object sender, RoutedEventArgs e)
{
ACLBox.Text = _manage.getAclList();
}
public string ACLBoxText
{
get { return aclText; }
set { aclText = value; OnNotifyPropertyChanged("ACLBoxText"); }
}
private void OnNotifyPropertyChanged(string v)
{
var handler = PropertyChanged;
if (handler != null)
handler(this, new PropertyChangedEventArgs(v));
throw new NotImplementedException();
}
}
}
Upon initializing, the string flashes for a second then disappears. Why?
Probably because you are "overwriting" the value of the ACLBoxText source property, which is initially displayed in the TextBlock, when you set the Text property of the TextBlock in your Loaded event handler.
If the TextBlock is empty once the UI has been loaded you should make sure that the _manage.getAclList() method returns the string that you expect it to return. You could temporarily try to assign the Text property to a "static" value:
private void ACLBox_Loaded(object sender, RoutedEventArgs e)
{
ACLBox.Text = "TEXT";
}
But I agree that it doesn't make much sense to first bind the Text property of the TextBlock to a source property in the XAML markup and then handle the Loaded event of the same TextBlock and set its Text property to a new value in this event handler. But I guess you have your reasons...
Note that binding that you define in the XAML markup will get reset when you programmatically set the Text property in your Loaded handler though.
So you should either don't bind the Text property in the XAML markup, or don't handle the Loaded event and set the Text property programmatically. It's one or the other but not both.
I figured out the problem. This is my first C# project and first time ever using Xaml (wpf) so I misunderstood binding. I bound the text like I did in the primary gui. The text is never getting triggered within this gui so I could only see the text flash because of loaded but then the text binding reset the textbox to nothing. When I changed my text to not be bound then everything works as I wanted. Lesson learned. Binding is only needed when accessing a textbox from within .cs files. It is not needed within xaml.cs. Since my text would only ever be triggered by xaml.cs just setting text the usual way(ie textbox.text = "whatever") does what I need. Thank you everyone for your help. I understand binding much, much better now. Java does things differently. :)
As Ed Plunkett has already mentioned, you should use your ACLBoxText backing variable instead of resetting the control value.
Something like this will work:
private void ACLBox_Loaded(object sender, RoutedEventArgs e)
{
ACLBoxText = _manage.getAclList();
}
Unfortunately, the view doesn't know about changes to backing properties unless you tell it that something changed. You need to implement INotifyPropertyChanged:
private string _aclBoxText;
public string ACLBoxText {
get { return _aclBoxText; }
set {
_aclBoxText = value;
OnNotifyPropertyChanged("ACLBoxText");
}
}
protected void OnNotifyPropertyChanged(string name)
{
var handler = PropertyChanged;
if (handler != null)
handler(this, new PropertyChangedEventArgs(name));
}
public event PropertyChangedEventHandler PropertyChanged;
I am trying to make an auction application for my course.
namespace Auction
{
/// <summary>
/// Interaction logic for MainWindow.xaml
/// </summary>
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
GetData("SELECT * FROM Produs");
btnLogout.Visibility = System.Windows.Visibility.Hidden;
btnAdd.Visibility = System.Windows.Visibility.Hidden;
btnBid.Visibility = System.Windows.Visibility.Hidden;
tb.Visibility = System.Windows.Visibility.Hidden;
}
private void GetData(string SelectCommand)
{
SqlConnection conn = new SqlConnection(#"Data Source=ISAAC;Initial Catalog=licitatie;Integrated Security=True");
conn.Open();
SqlCommand cmd = new SqlCommand(SelectCommand);
cmd.Connection = conn;
SqlDataAdapter sda = new SqlDataAdapter(cmd);
DataTable dt = new DataTable("prod");
sda.Fill(dt);
myGrid.DataContext = dt;
}
private void btnLogin_Click(object sender, RoutedEventArgs e)
{
Login login = new Login();
login.Show();
Close();
}
private void Button_Click(object sender, RoutedEventArgs e)
{
Countdown(30, TimeSpan.FromSeconds(1), cur => tb.Text = cur.ToString());
}
void Countdown(int count, TimeSpan interval, Action<int> ts)
{
var dt = new System.Windows.Threading.DispatcherTimer();
dt.Interval = interval;
dt.Tick += (_, a) =>
{
if (count-- == 0)
{
MessageBox.Show("You have won this product!");
dt.Stop();
}
else
ts(count);
};
ts(count);
dt.Start();
}
private void btnLogout_Click(object sender, RoutedEventArgs e)
{
MainWindow main = new MainWindow();
main.Show();
Close();
MessageBox.Show("You are not logged. Please log in to bid", "Failed",
MessageBoxButton.OK, MessageBoxImage.Information);
}
private void btnAdd_Click(object sender, RoutedEventArgs e)
{
Register reg = new Register();
reg.Show();
Close();
}
private void DataGrid_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
var grid = sender as DataGrid;
var selected = grid.SelectedItem;
if (selected == grid.SelectedItem)
{
btnBid.Visibility = System.Windows.Visibility.Visible;
}
}
private void UpdateColumn()
{
}
}
}
This is main page you need to login. I read data from database. The problem is when I press bid button many times it is just resetting, but in background is working on. What do I need to do?
<Window x:Class="Auction.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="MainWindow" Height="500" Width="800">
<Grid Margin="0,148,0,3" Name="myGrid" Background="#FF00286E">
<Grid.ColumnDefinitions>
<ColumnDefinition Width="29*"/>
<ColumnDefinition Width="15*"/>
<ColumnDefinition Width="0*"/>
</Grid.ColumnDefinitions>
<Grid HorizontalAlignment="Left" Height="66" Margin="0,-68,0,0" VerticalAlignment="Top"
Width="792" Background="#FF00286E" Grid.ColumnSpan="2">
<Grid.ColumnDefinitions>
<ColumnDefinition Width="12*"/>
<ColumnDefinition Width="13*"/>
</Grid.ColumnDefinitions>
<Button Content="Login" HorizontalAlignment="Left" Margin="10,10,0,0" VerticalAlignment="Bottom"
Width="102" Height="35" Name="btnLogin" Click="btnLogin_Click">
<Button.Template>
<ControlTemplate TargetType="Button">
<TextBlock TextDecorations="Underline" Margin="0,0,0,-19" FontSize="24"
FontFamily="Verdana" FontWeight="Bold" FontStyle="Italic">
<ContentPresenter />
</TextBlock>
</ControlTemplate>
</Button.Template>
</Button>
<Button Content="Logout" Grid.Column="1" HorizontalAlignment="Left" Margin="300,10,0,0" VerticalAlignment="Bottom"
Width="102" Height="35" Name="btnLogout" Click="btnLogout_Click">
<Button.Template>
<ControlTemplate TargetType="Button">
<TextBlock TextDecorations="Underline" Margin="0,0,0,-19" FontSize="24"
FontFamily="Verdana" FontWeight="Bold" FontStyle="Italic">
<ContentPresenter />
</TextBlock>
</ControlTemplate>
</Button.Template>
</Button>
</Grid>
<Grid HorizontalAlignment="Left" Height="78" Margin="0,-146,0,0" VerticalAlignment="Top" Width="792"
Grid.ColumnSpan="2" Background="#FF98BFD4">
<Grid.ColumnDefinitions>
<ColumnDefinition Width="769*"/>
<ColumnDefinition Width="31*"/>
</Grid.ColumnDefinitions>
<Label Content="Welcome to Auction Application. Please Login to bid!" HorizontalAlignment="Center" Margin="44,28,0,0" VerticalAlignment="Top"
Height="40" Width="748" BorderThickness="3" FontSize="18" FontWeight="Bold" FontFamily="Verdana" Background="#FF98BFD4" Grid.ColumnSpan="2"/>
</Grid>
<Button Content="Bid" Grid.Column="1" HorizontalAlignment="Left" Margin="10,10,0,0"
VerticalAlignment="Top" Width="103" Height="29" FontSize="20" FontFamily="Verdana" FontStyle="Italic"
FontWeight="ExtraBold" Click="Button_Click" Name="btnBid"/>
<Button Content="Add User" Grid.Column="1" HorizontalAlignment="Left" Margin="10,255,0,0"
VerticalAlignment="Top" Width="103" Height="31" Name="btnAdd" Click="btnAdd_Click"/>
<DataGrid HorizontalAlignment="Left" Margin="10,10,0,0" VerticalAlignment="Top"
Height="298" Width="502" Name="dataGrid1" ItemsSource="{Binding}"
SelectionChanged="DataGrid_SelectionChanged" AlternatingRowBackground="Coral">
</DataGrid>
<TextBox Grid.Column="1" HorizontalAlignment="Left" Height="48" Margin="10,119,0,0" TextWrapping="Wrap"
VerticalAlignment="Top" Width="144" Name="tb" FontSize="20" FontWeight="Bold" FontStyle="Italic" IsReadOnly="True"/>
</Grid>
</Window>
If I understand correctly, each time the user clicks the Bid button, you need to reset the timer. However, the previous timer continues. I haven't pasted your code into a project to test, but it appears to me that you need to make the dispatch timer a class field or property like this:
private DispatchTimer _dt = new System.Windows.Threading.DispatcherTimer();
Inside the event handler for Bid, stop the current _dt first followed by instantiating the new timer:
_dt.Stop();
_dt = new System.Windows.Threading.DispatcherTimer();
Try this change:
namespace Auction
{
/// <summary>
/// Interaction logic for MainWindow.xaml
/// </summary>
public partial class MainWindow : Window
{
//Class level field:
private DispatchTimer _dt = new System.Windows.Threading.DispatcherTimer();
public MainWindow()
{
InitializeComponent();
GetData("SELECT * FROM Produs");
btnLogout.Visibility = System.Windows.Visibility.Hidden;
btnAdd.Visibility = System.Windows.Visibility.Hidden;
btnBid.Visibility = System.Windows.Visibility.Hidden;
tb.Visibility = System.Windows.Visibility.Hidden;
}
private void GetData(string SelectCommand)
{
SqlConnection conn = new SqlConnection(#"Data Source=ISAAC;Initial Catalog=licitatie;Integrated Security=True");
conn.Open();
SqlCommand cmd = new SqlCommand(SelectCommand);
cmd.Connection = conn;
SqlDataAdapter sda = new SqlDataAdapter(cmd);
DataTable dt = new DataTable("prod");
sda.Fill(dt);
myGrid.DataContext = dt;
}
private void btnLogin_Click(object sender, RoutedEventArgs e)
{
Login login = new Login();
login.Show();
Close();
}
private void Button_Click(object sender, RoutedEventArgs e)
{
Countdown(30, TimeSpan.FromSeconds(1), cur => tb.Text = cur.ToString());
}
void Countdown(int count, TimeSpan interval, Action<int> ts)
{
this._dt.Stop();
this._dt = new System.Windows.Threading.DispatcherTimer();
this._dt.Interval = interval;
this._dt.Tick += (_, a) =>
{
if (count-- == 0)
{
MessageBox.Show("You have won this product!");
this._dt.Stop();
}
else
ts(count);
};
ts(count);
this._dt.Start();
}
private void btnLogout_Click(object sender, RoutedEventArgs e)
{
MainWindow main = new MainWindow();
main.Show();
Close();
MessageBox.Show("You are not logged. Please log in to bid", "Failed",
MessageBoxButton.OK, MessageBoxImage.Information);
}
private void btnAdd_Click(object sender, RoutedEventArgs e)
{
Register reg = new Register();
reg.Show();
Close();
}
private void DataGrid_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
var grid = sender as DataGrid;
var selected = grid.SelectedItem;
if (selected == grid.SelectedItem)
{
btnBid.Visibility = System.Windows.Visibility.Visible;
}
}
private void UpdateColumn()
{
}
}
}
I have a listbox like this:
<toolkit:ListPicker Name="lstBoxBaseUnitOfMeasure" Width="100" Margin="0,4,0,0">
<toolkit:ListPicker.Items>
<TextBlock Text="EACH" Height="30"/>
<TextBlock Text="GRAM" Height="30"/>
</toolkit:ListPicker.Items>
</toolkit:ListPicker>
I would like to send selected item to Local Database like this:
private void AddProduct_Click(object sender, RoutedEventArgs e)
{
TblProductsToOrder newProductToOrder = new TblProductsToOrder
{
OrderNId = selectedID,
Quantity = int.Parse(txtQuantity.Text),
**BaseUnitOfMeasure = ??????????????**
};
}
ListPicker fires an event,SelectionChanged whenever a item is selected. You will need to listen to that event
<toolkit:ListPicker Name="lstBoxBaseUnitOfMeasure" Width="100" Margin="0,4,0,0" SelectionChanged="listPicker_SelectionChanged">
<toolkit:ListPicker.Items>
<TextBlock Text="EACH" Height="30"/>
<TextBlock Text="GRAM" Height="30"/>
</toolkit:ListPicker.Items>
</toolkit:ListPicker>
private void listPicker_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
if (lstBoxBaseUnitOfMeasure.SelectedItem != null)
{
var texBlock = (TextBlock) lstBoxBaseUnitOfMeasure.SelectedItem;
selectedUnit = texBlock.Text;
TblProductsToOrder newProductToOrder = new TblProductsToOrder
{
OrderNId = selectedID,
Quantity = int.Parse(txtQuantity.Text),
BaseUnitOfMeasure = selectedUnit
};
}
}
Assuming that BaseUnitOfMeasure property is of type String, you can try this way :
String selectedUnit = "";
if(lstBoxBaseUnitOfMeasure.SelectedItem != null)
{
var selectedTextBlock = (TextBlock)lstBoxBaseUnitOfMeasure.SelectedItem;
selectedUnit = selectedTextBlock.Text;
}
TblProductsToOrder newProductToOrder = new TblProductsToOrder
{
OrderNId = selectedID,
Quantity = int.Parse(txtQuantity.Text),
BaseUnitOfMeasure = selectedUnit
};