I'm working with windows phone 8 apps and want to add augmented reality feature and I'm using GART, but I experiencing the same issue
in there and even there is a solution by Igor Ralic by adding canvas.zindex to 1, I'm still experiencing the same issue (the items in world view flicker and disappear), so maybe there is anybody in here that having much better solution? I'm using mvvm patern to work with this AR
Here is my approach with mvvm
This is my mainviewmodel
private ObservableCollection<ARItem> _ardisplayLocation = null;
public ObservableCollection<ARItem> ardisplayLocation
{
get { return _ardisplayLocation; }
set { this.SetProperty(ref this._ardisplayLocation, value); }
}
private void UpdateTransport()
{
try
{
myMessage = "Loading web server data...";
WebClient client = new WebClient();
Uri uri = new Uri(transportURL1 + latitude + "%2C" + longitude + transportURL2, UriKind.Absolute);
client.DownloadStringCompleted += (s, e) =>
{
MainPage mainpage = new MainPage();
mainpage.RefreshButton();
if (e.Error == null)
{
RootObject result = JsonConvert.DeserializeObject<RootObject>(e.Result);
hereRestProperty = new ObservableCollection<Item>(result.results.items);
for (int i = 0; i < hereRestProperty.Count; i++)
{
ardisplayLocation.Add(new CityPlace()
{
GeoLocation = new GeoCoordinate(hereRestProperty[i].coordinate.Latitude,hereRestProperty[i].coordinate.Longitude),
Content = hereRestProperty[i].title,
Description = hereRestProperty[i].vicinity
});
}
}
else
{
isFailed = Visibility.Visible;
myMessage = "Failed to load web server data, please refresh";
}
isBusy = false;
};
client.DownloadStringAsync(uri);
}
catch (Exception)
{
isBusy = false;
isFailed = Visibility.Visible;
myMessage = "Something wrong happen, please refresh";
}
}
and here is my ArDisplay.xaml.cs
private MainViewModel mvm { get { return this.DataContext as MainViewModel; } }
public ArDisplay()
{
InitializeComponent();
DataContext = App.ViewModel;
}
protected override void OnNavigatedTo(System.Windows.Navigation.NavigationEventArgs e)
{
ardisplay.StartServices();
ardisplay.ARItems = mvm.ardisplayLocation;
base.OnNavigatedTo(e);
}
protected override void OnNavigatedFrom(System.Windows.Navigation.NavigationEventArgs e)
{
ardisplay.StopServices();
base.OnNavigatedFrom(e);
}
and my xaml
<gart:ARDisplay Name="ardisplay" AttitudeRefreshRate="50" MovementThreshold="10">
<gart:VideoPreview x:Name="videoPreview" Canvas.ZIndex="1"/>
<gart:WorldView x:Name="worldView" Canvas.ZIndex="1" ItemTemplate="{StaticResource CityItemTemplate}" MinItemScale="0.1" MaxItemScale="1.0" FarClippingPlane="300.0" NearClippingPlane="1.0"/>
<gart:HeadingIndicator x:Name="headingIndicator" Canvas.ZIndex="1" Width="300" Height="300" HorizontalAlignment="Center" VerticalAlignment="Center"/>
</gart:ARDisplay>
and my data template
<DataTemplate x:Key="CityItemTemplate">
<Border BorderBrush="Black" BorderThickness="4" CornerRadius="8" Background="#FF003847" Width="320">
<StackPanel Margin="4">
<TextBlock x:Name="NameBlock" TextWrapping="NoWrap" Text="{Binding Content}" FontSize="38" VerticalAlignment="Center" Margin="0,0,4,0" Grid.Column="1" TextTrimming="WordEllipsis"/>
<TextBlock x:Name="DescriptionBlock" TextWrapping="Wrap" Text="{Binding Description}" FontSize="24" VerticalAlignment="Center" Margin="0,0,4,0" Grid.Column="1" TextTrimming="WordEllipsis" MaxHeight="168"/>
</StackPanel>
</Border>
</DataTemplate>
Canvas.ZIndex was missing from your DataTemplate
<DataTemplate x:Key="CityItemTemplate">
<Border BorderBrush="Black" BorderThickness="4" CornerRadius="8" Background="#FF003847" Width="320" Canvas.ZIndex="2">
<StackPanel Margin="4">
<TextBlock x:Name="NameBlock" TextWrapping="NoWrap" Text="{Binding Content}" FontSize="38" VerticalAlignment="Center" Margin="0,0,4,0" Grid.Column="1" TextTrimming="WordEllipsis"/>
<TextBlock x:Name="DescriptionBlock" TextWrapping="Wrap" Text="{Binding Description}" FontSize="24" VerticalAlignment="Center" Margin="0,0,4,0" Grid.Column="1" TextTrimming="WordEllipsis" MaxHeight="168"/>
</StackPanel>
</Border>
</DataTemplate>
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);
}
}
}
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 have a wpf application and I want to be able to delete a column from a grid and then have the other columns repositioned themselves (i.e. if the users deletes the first column all other columns move one to the left, if the user deletes the second column all other columns after the second one moves to the left) by the event of clicking a button. Currently I am only able to hide the items in the column, it leaves a white space which I don't want.
private void SetColumnWidthCol1()
{
Col2.Width = new GridLength(150);
Col3.Width = new GridLength(150);
Col4.Width = new GridLength(150);
}
private void SetColumnWidthCol2()
{
Col1.Width = new GridLength(150);
Col3.Width = new GridLength(150);
Col4.Width = new GridLength(150);
}
private void SetColumnWidthCol3()
{
Col1.Width = new GridLength(150);
Col2.Width = new GridLength(150);
Col4.Width = new GridLength(150);
}
private void SetColumnWidthCol4()
{
Col1.Width = new GridLength(150);
Col2.Width = new GridLength(150);
Col3.Width = new GridLength(150);
Col5.Width = new GridLength(150);
Col6.Width = new GridLength(150);
}
private void SetColumnWidthCol5()
{
Col1.Width = new GridLength(150);
Col2.Width = new GridLength(150);
Col3.Width = new GridLength(150);
Col4.Width = new GridLength(150);
Col6.Width = new GridLength(150);
}
private void SetColumnWidthCol6()
{
Col1.Width = new GridLength(150);
Col2.Width = new GridLength(150);
Col3.Width = new GridLength(150);
Col4.Width = new GridLength(150);
Col5.Width = new GridLength(150);
}
private void CloseRock_Click(object sender, RoutedEventArgs e)
{
RockLabel.Visibility = System.Windows.Visibility.Hidden;
CloseRock.Visibility = System.Windows.Visibility.Hidden;
}
private void CloseContacts_Click(object sender, RoutedEventArgs e)
{
ContactsLabel.Visibility = System.Windows.Visibility.Hidden;
CloseContacts.Visibility = System.Windows.Visibility.Hidden;
}
private void CloseFluid_Click(object sender, RoutedEventArgs e)
{
FluidLabel.Visibility = System.Windows.Visibility.Hidden;
CloseFluid.Visibility = System.Windows.Visibility.Hidden;
}
private void CloseRegions_Click(object sender, RoutedEventArgs e)
{
RegionsLabel.Visibility = System.Windows.Visibility.Hidden;
CloseRegions.Visibility = System.Windows.Visibility.Hidden;
}
private void CloseProbabilities_Click(object sender, RoutedEventArgs e)
{
ProbabilitiesLabel.Visibility = System.Windows.Visibility.Hidden;
CloseProbabilities.Visibility = System.Windows.Visibility.Hidden;
}
private void CloseEconomics_Click(object sender, RoutedEventArgs e)
{
EconomicsLabel.Visibility = System.Windows.Visibility.Hidden;
CloseEconomics.Visibility = System.Windows.Visibility.Hidden;
}
}
XAML
<Window
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:syncfusion="http://schemas.syncfusion.com/wpf"
x:Class="ItemWrapPanel.MainWindow"
Title="MainWindow" Height="350" Width="1000">
<Window.Resources>
<LinearGradientBrush x:Key="LabelBackground" StartPoint="0,0" EndPoint="0,1">
<GradientStop Color="#FFEFEEEE" Offset="0"/>
<GradientStop Color="#E7E7E7E7" Offset="1"/>
</LinearGradientBrush>
<LinearGradientBrush x:Key="selectedHeaderBackground" StartPoint="0,0" EndPoint="0,1">
<GradientStop Color="#F6CD1D" Offset="0"/>
<GradientStop Color="#EBA32A" Offset="1"/>
</LinearGradientBrush>
</Window.Resources>
<Grid x:Name="MainGrid">
<Grid.RowDefinitions>
<RowDefinition/>
</Grid.RowDefinitions>
<Grid.ColumnDefinitions>
<ColumnDefinition x:Name="Col1"/>
<ColumnDefinition x:Name="Col2"/>
<ColumnDefinition x:Name="Col3"/>
<ColumnDefinition x:Name="Col4"/>
<ColumnDefinition x:Name="Col5"/>
<ColumnDefinition x:Name="Col6"/>
</Grid.ColumnDefinitions>
<Label x:Name="RockLabel"
Background="{StaticResource LabelBackground}"
Content="Rock Properties"
Grid.Row="0"
Grid.Column="0"
MouseUp="RockLabel_MouseDoubleClick"
VerticalAlignment="Top"/>
<Label x:Name="ContactsLabel"
Content="Contacts"
Background="{StaticResource LabelBackground}"
Grid.Column="1"
Grid.Row="0"
MouseUp="ContactsLabel_MouseDoubleClick"
VerticalAlignment="Top"/>
<Label x:Name="FluidLabel"
Content="Fluid Properties"
Background="{StaticResource LabelBackground}"
Grid.Column="2"
Grid.Row="0"
MouseUp="FluidLabel_MouseDoubleClick"
VerticalAlignment="Top"/>
<Label x:Name="RegionsLabel"
Content="Regions"
Background="{StaticResource LabelBackground}"
Grid.Column="3"
Grid.Row="0"
MouseUp="RegionsLabel_MouseDoubleClick"
VerticalAlignment="Top"/>
<Label x:Name="ProbabilitiesLabel"
Content="Probabilities"
Background="{StaticResource LabelBackground}"
Grid.Column="4"
Grid.Row="0"
MouseUp="ProbabiltitesLabel_MouseDoubleClick"
VerticalAlignment="Top"/>
<Label x:Name="EconomicsLabel"
Content="Economics"
Background="{StaticResource LabelBackground}"
Grid.Column="5"
Grid.Row="0"
MouseUp="EconomicsLabel_MouseDoubleClick"
VerticalAlignment="Top"/>
<Button x:Name="Resetbtn" Content="Restore" HorizontalAlignment="Left" VerticalAlignment="Top" Width="75" Click="Reset_Click" Margin="0,59,0,0"/>
<Button Name="CloseRock" Content="X" HorizontalAlignment="Right" Margin="0,2,0,0" VerticalAlignment="Top" Width="24" Grid.Column="0" Grid.Row="0" Click="CloseRock_Click"/>
<Button Name="CloseContacts" Content="X" HorizontalAlignment="Right" Margin="0,2,2,0" VerticalAlignment="Top" Width="24" Grid.Column="1" Grid.Row="0" Click="CloseContacts_Click"/>
<Button Name="CloseFluid" Content="X" HorizontalAlignment="Right" Margin="0,2,2,0" VerticalAlignment="Top" Width="24" Grid.Column="2" Grid.Row="0" Click="CloseFluid_Click"/>
<Button Name="CloseRegions" Content="X" HorizontalAlignment="Right" Margin="0,2,1,0" VerticalAlignment="Top" Width="24" Grid.Column="3" Grid.Row="0" Click="CloseRegions_Click"/>
<Button Name="CloseProbabilities" Content="X" HorizontalAlignment="Right" Margin="0,2,1,0" VerticalAlignment="Top" Width="24" Grid.Column="4" Grid.Row="0" Click="CloseProbabilities_Click"/>
<Button Name="CloseEconomics" Content="X" HorizontalAlignment="Right" Margin="0,2,1,0" VerticalAlignment="Top" Width="24" Grid.Column="5" Grid.Row="0" Click="CloseEconomics_Click"/>
</Grid>
Instead of Visibility.Hidden make them Visibility.Collapsed.
Like -
private void CloseContacts_Click(object sender, RoutedEventArgs e)
{
ContactsLabel.Visibility = System.Windows.Visibility.Collapsed;
CloseContacts.Visibility = System.Windows.Visibility.Collapsed;
}
I'm populating a DataGrid with sorting and grouping in WPF and I want to implement a progress indicator to the user for them to know that the current query is still running in the background. I'm trying to use the ProgressRing of Mahapps but i don't know how do I implement it. Below is my code.
Code Behind
void InitSongs()
{
this.Dispatcher.Invoke((Action)(() => {
DataTable dtSong = new DataTable();
ICollection<Song> songList = new ObservableCollection<Song>();
using (SqlConnection conn = new SqlConnection(#"Server=.\MSSQL2008R2;Database=MVCDB;Trusted_Connection=True;"))
{
string sqlCmd = "SELECT TOP 1000 * FROM SongDb";
conn.Open();
using (SqlCommand cmd = new SqlCommand(sqlCmd, conn))
{
cmd.CommandType = System.Data.CommandType.Text;
cmd.CommandText = sqlCmd;
cmd.CommandTimeout = 120;
dtSong.Load(cmd.ExecuteReader());
}
}
for (int i = 0; i <= dtSong.Rows.Count - 1; i++)
{
songList.Add(new Song(Convert.ToInt32(dtSong.Rows[i][0]),
dtSong.Rows[i][1].ToString(),
dtSong.Rows[i][2].ToString(),
Convert.ToInt64(dtSong.Rows[i][3]),
dtSong.Rows[i][4].ToString(),
Convert.ToBoolean(dtSong.Rows[i][5])));
}
dgSongs.ItemsSource = songList;
ICollectionView view = CollectionViewSource.GetDefaultView(dgSongs.ItemsSource);
view.SortDescriptions.Add(new SortDescription("Artist", ListSortDirection.Ascending));
//view.SortDescriptions.Add(new SortDescription("Title", ListSortDirection.Ascending));
view.GroupDescriptions.Add(new PropertyGroupDescription("Artist"));
}));
}
private void btnGetSongs_Click(object sender, RoutedEventArgs e)
{
bw.WorkerReportsProgress = true;
bw.WorkerSupportsCancellation = true;
bw.DoWork += new DoWorkEventHandler(bw_DoWork);
bw.RunWorkerCompleted += new RunWorkerCompletedEventHandler(bw_RunWorkerCompleted);
bw.ProgressChanged += new ProgressChangedEventHandler(bw_ProgressChanged);
progress1.IsActive = true;
progress1.Visibility = System.Windows.Visibility.Visible;
bw.RunWorkerAsync();
}
void bw_DoWork(object sender, DoWorkEventArgs e)
{
InitSongs();
}
void bw_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
{
progress1.IsActive = false;
progress1.Visibility = Visibility.Collapsed;
}
MainWindow.xaml
<Controls:MetroWindow x:Class="PalletTaggingWpf.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:Controls="clr-namespace:MahApps.Metro.Controls;assembly=MahApps.Metro"
Title="Pallet Tagging" Height="500" Width="500" ShowIconOnTitleBar="True"
WindowStartupLocation="CenterScreen"
GlowBrush="{DynamicResource AccentColorBrush}"
BorderBrush="{DynamicResource AccentColorBrush}"
EnableDWMDropShadow="True"
BorderThickness="1">
<TabControl>
<TabItem Header="Songs">
<Grid>
<Grid.RowDefinitions>
<RowDefinition Height="Auto"></RowDefinition>
<RowDefinition></RowDefinition>
</Grid.RowDefinitions>
<StackPanel>
<Button Name="btnGetSongs" Content="Get Songs" Click="btnGetSongs_Click"></Button>
</StackPanel>
<DataGrid Grid.Row="1" Name="dgSongs" ItemsSource="{Binding}">
<DataGrid.GroupStyle>
<GroupStyle>
<GroupStyle.HeaderTemplate>
<DataTemplate>
<StackPanel>
<TextBlock Text="{Binding Path=Name}" />
</StackPanel>
</DataTemplate>
</GroupStyle.HeaderTemplate>
<GroupStyle.ContainerStyle>
<Style TargetType="{x:Type GroupItem}">
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="{x:Type GroupItem}">
<Expander IsExpanded="True">
<Expander.Header>
<StackPanel Orientation="Horizontal">
<TextBlock Text="{Binding Path=Name}" />
<TextBlock Text="{Binding Path=ItemCount}"/>
<TextBlock Text="Items"/>
</StackPanel>
</Expander.Header>
<ItemsPresenter />
</Expander>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
</GroupStyle.ContainerStyle>
</GroupStyle>
</DataGrid.GroupStyle>
</DataGrid>
</Grid>
</TabItem>
</TabControl>
PS: I'm using VS2010 for this
XAML
<StackPanel>
<Button Name="btnGetSongs" Content="Get Songs" Click="btnGetSongs_Click"></Button>
<ProgressRing x:Name="progress1"/> <!-- Without MahApps -->
</StackPanel>
CS
this.Dispatcher.Invoke((Action)(() => {
progress1.IsActive = true;
progress1.Visibility = Visibility.Visible;
DataTable dtSong = new DataTable();
//All Steps will go as stated
view.GroupDescriptions.Add(new PropertyGroupDescription("Artist"));
progress1.IsActive = false;
progress1.Visibility = Visibility.Collapsed;
}));
MahApps
XAML
<StackPanel>
<Button Name="btnGetSongs" Content="Get Songs" Click="btnGetSongs_Click"></Button>
<Controls:ProgressRing IsActive="False" Visibility="Collapsed" Name="progress1" />
</StackPanel>
CS
this.Dispatcher.Invoke((Action)(() => {
progress1.IsActive = true;
progress1.Visibility = Visibility.Visible;
DataTable dtSong = new DataTable();
//All Steps will go as stated
view.GroupDescriptions.Add(new PropertyGroupDescription("Artist"));
progress1.IsActive = false;
progress1.Visibility = Visibility.Collapsed;
}));
After user get the end of longlistselector ItemRealized event fires items add successfully. But the button's tag is empty (for added items), for items that I got first time button's tag isn't null.
This is my xaml DataTemplate:
<DataTemplate x:Key="TitleSongDataTemplate" x:Name="Titledata">
<Border Background="{StaticResource PhoneForegroundBrush}" Margin="0,0,12,12">
<Grid x:Name="GridOfButtons" Background="{StaticResource PhoneForegroundBrush}" >
<Grid Margin="0, -6, -7, 0"
HorizontalAlignment="Right"
VerticalAlignment="Top" Height="81" Width="83">
<Button
Content=""
FontFamily="Segoe UI Symbol"
Style="{StaticResource RoundButton}"
x:Name="AddToMySongsButton"
Tag="{Binding Song}"
Background="{StaticResource PhoneBackgroundBrush}"
Click="AddToMySongsButton_Click"/>
</Grid>
<Grid
VerticalAlignment="Top"
HorizontalAlignment="Left"
Margin="-17,-6,0,0" Height="81" Width="95">
<Button FontFamily="Segoe UI Symbol"
Content=""
Style="{StaticResource RoundButton}" Margin="10,0,0,0"
x:Name="PlayButton"
Background="{StaticResource PhoneBackgroundBrush}"
Tag="{Binding Song}"
Click="PlayButton_Click"/>
</Grid>
<Grid
HorizontalAlignment="Center"
VerticalAlignment="Top"
Margin="69,-7,60,0" Height="82" Width="84">
<Button Style="{StaticResource RoundButton}"
Content=""
FontFamily="Segoe UI Symbol"
x:Name="DownloadButton"
Margin="-5,0,0,0"
Background="{StaticResource PhoneBackgroundBrush}"
Tag="{Binding Song}"
Click="DownloadButton_Click"/>
</Grid>
<StackPanel VerticalAlignment="Bottom">
<TextBlock Text="{Binding Title}" Foreground="{StaticResource PhoneBackgroundBrush}" Margin="6 , 4, 6, 4"/>
<TextBlock Text="{Binding Artist}" Foreground="Gray" Opacity="0.75" Margin="6, 0, 0, 6"/>
</StackPanel>
</Grid>
</Border>
</DataTemplate>
My pivot:
<phone:Pivot x:Name="MainTitle">
<phone:PivotItem Header="Rock">
<Grid>
<phone:LongListSelector x:Name="RockLongList"
GridCellSize="220,150"
LayoutMode="Grid"
ItemTemplate="{StaticResource TitleSongDataTemplate}"
ItemRealized="RockLongList_ItemRealized"/>
<TextBlock x:Name="RockText"
Text="Загрузка..."
FontSize="60"
Opacity="0.5"
Style="{StaticResource LongListSelectorGroupHeaderLetterTileStyle}"
Margin="0,10,10,10"
TextWrapping="Wrap"
HorizontalAlignment="Right"
Width="436"/>
</Grid>
</phone:PivotItem>
Here my infinity scrooling realization:
1.I fired ItemRealized
private void RockLongList_ItemRealized(object sender, ItemRealizationEventArgs e)
{
var nownum = offset + 50;
if (nownum >= usercount)
{
MainTitle.Title = "All songs've downloaded";
}
else
{
SpecialSongs.SongJSON song = e.Container.Content as SpecialSongs.SongJSON;
if (song != null)
{
int myoffset = 2;
// Only if there is no data that is currently getting loaded would be initiate the loading again
if (!isCurrentlyLoading && defaultBindList.Count - defaultBindList.IndexOf(song) <= myoffset)
{
LoadDataFromSource();
}
}
}
}
And finally:
private void LoadDataFromSource()
{
this.Dispatcher.BeginInvoke(() =>
{
MainTitle.Title = "Downloading test...";
});
//progressBar.IsVisible = true;
isCurrentlyLoading = true;
string UsersUri = string.Format("https://api.vk.com/method/audio.get?&count=50&access_token={0}&user_id={1}&version=4.92&offset={2}", AccessToken, uID, offset);
//var query = string.Format(datasourceUrl, currentPage);
WebClient client = new WebClient();
client.DownloadStringCompleted += client_DownloadStringCompleted;
client.DownloadStringAsync(new Uri(UsersUri));
}
private void client_DownloadStringCompleted(object sender, DownloadStringCompletedEventArgs e)
{
//Here handle exception
using (var reader = new MemoryStream(Encoding.Unicode.GetBytes(e.Result)))
{
SpecialSongs songs = JsonConvert.DeserializeObject<SpecialSongs>(e.Result);
this.Dispatcher.BeginInvoke(() =>
{
foreach (var tracks in songs.songs)
{
rockBindList.Add(tracks);
MainTitle.Title = "Downloaded test...";
}
RockLongList.ItemsSource = rockBindList;
isCurrentlyLoading = false;
//progressBar.IsVisible = false;
});
}
offset += 50;
}
This code shows why i need button's tag property:
private void DownloadButton_Click(object sender, RoutedEventArgs e)
{
try
{
SpecialSongs.SongJSON songdgd = (SpecialSongs.SongJSON)(sender as Button).Tag;
this.Download.Message = songdgd.Artist + "\n" + songdgd.Title;
string StringToSave = "shared/transfers/" + songdgd.Artist + songdgd.Title;
var linktosave = StringToSave.Replace(" ", "");
transferRequest = new BackgroundTransferRequest(new Uri(songdgd.URI, UriKind.RelativeOrAbsolute)) { Method = "GET" };
var uri = new Uri(linktosave, UriKind.Relative);
songdgd.URI = linktosave.Replace("shared/transfers/", "");
var json = JsonConvert.SerializeObject(songdgd);
var name = linktosave.Replace("shared/transfers/", "");
transferRequest.Tag = "json" + json + "json" + "uri" + name + "uri";
transferRequest.TransferPreferences = TransferPreferences.AllowCellularAndBattery;
transferRequest.DownloadLocation = uri;
try
{
BackgroundTransferService.Add(transferRequest);
}
catch
{
MessageBox.Show("Эта песня уже загружается.");
}
}
catch { MessageBox.Show("Error while downloading"); }
}
Thanks.