Hey all I am not sure why I am having such a hard time with this but I am needing to be able to change a tiles isEnabled property depending on if my program detects an internet connection or not.
The WPF code that I am using and needing to change is the following:
<dxlc:TileLayoutControl x:Name="tileLayoutControl1" Margin="150,63,153,57" Padding="5"
AllowAddFlowBreaksDuringItemMoving="False" AllowItemMoving="False" Orientation="Horizontal" ScrollBars="None"
TileClick="tileLayoutControl1_TileClick">
</dxlc:TileLayoutControl>
This gets populated by the code behind on startup:
private void createMenu()
{
List<String> menuIcons = new List<string>();
menuIcons.Add("gamesIcon.png");
menuIcons.Add("movieIcon.png");
menuIcons.Add("musicIcon.png");
menuIcons.Add("televisionIcon.png");
menuIcons.Add("youTubeIcon.png");
menuIcons.Add("androidIcon.png");
foreach (String item in menuIcons)
{
Image finalImage = new Image();
BitmapImage image = new BitmapImage();
image.BeginInit();
image.UriSource = new Uri("/img/" + item.ToString(), UriKind.Relative);
image.EndInit();
finalImage.Source = image;
image = null;
tileLayoutControl1.Children.Add(new Tile()
{
Content = finalImage,
Name = item.ToString().Replace(".png", ""),
Tag = item.ToString().Replace(".png", "").Replace(".jpg", ""),
Width = 255,
Height = 288,
IsEnabled = false,
Margin = new Thickness(0, 0, 50, 20),
Background = Brushes.Transparent,
BorderThickness = new Thickness(0, 0, 0, 0)
}
}
}
and finally the code that I have checking the internet connection within a timer:
private bool checkInternet()
{
try
{
Ping myPing = new Ping();
PingReply reply = myPing.Send("google.com", 1000, new byte[32], new PingOptions());
return (reply.Status == IPStatus.Success);
}
catch (Exception)
{
return false;
}
}
public firstWindow()
{
InitializeComponent();
var startTimeSpan = TimeSpan.Zero;
var periodTimeSpan = TimeSpan.FromMinutes(5);
var timer = new System.Threading.Timer((e) =>
{
bool hasInternet = checkInternet();
TileLayoutControl test = (TileLayoutControl)this.tileLayoutControl1.FindName("youTubeIcon");
test.IsEnabled = true;
tileLayoutControl1.RegisterName("youTubeIcon", this.isEnabled = true);
}, null, startTimeSpan, periodTimeSpan);
}
I am currently not getting any errors for the lines:
TileLayoutControl test = (TileLayoutControl)this.tileLayoutControl1.FindName("youTubeIcon");
test.IsEnabled = true;
tileLayoutControl1.RegisterName("youTubeIcon", this.isEnabled = true);
But test is null and RegisterName doesn't seem to change the isEnabled property when I try to click on the tile.
I've also read that using Command="{Binding ClickCommand}" may be my answer but that seems to only pertain to MVVM type of patterns which I am not using for this particle program.
I also know that checking the tileLayoutCibtril1 has a Children property that does contain my dynamically created icons but tileLayoutCibtril1.Children does not have a .FindName proeprty.
So what am I missing?
Try to call ApplyTemplate on TileLayoutControl after foreach statement. The template for TileLayoutControl has not yet been applied and therefore FindName returns null. ApplyTemplate builds the current template’s visual tree
foreach (String item in menuIcons)
{
...
}
tileLayoutControl1.ApplyTemplate();
Related
I noted something wrong, either it's from me or a bug when experimenting with .Net MAUI.
I have an ObservableCollection property :
public ObservableCollection<LotoModel> Lotteries { get; set; } = new();
and an ObservableProperty (using community mvvm toolkit) :
[ObservableProperty]
public string _lotteriesCount = "A";
When ever I click/touch a Button I load my Lotteries collection. (tested with an hard coded 4 static LotoModel items) :
static GridModel _testGM1 = new GridModel { Name = "TEST Grid #1", Start = 0, End = 10, NumberOfDraw = 2 };
static GridModel _testGM2 = new GridModel { Name = "TEST Grid #2", Start = 0, End = 20, NumberOfDraw = 5 };
static GridModel _testGM3 = new GridModel { Name = "TEST Grid #3", Start = 0, End = 30, NumberOfDraw = 8 };
static GridModel _testGM4 = new GridModel { Name = "TEST Grid #4", Start = 0, End = 50, NumberOfDraw = 10 };
static LotoModel _testLM1 = new LotoModel { Name = "TEST Lottery #1", IsFavorite = true, Grids = new ObservableCollection<GridModel> { _testGM1, _testGM2 } };
static LotoModel _testLM2 = new LotoModel { Name = "TEST Lottery #2", IsFavorite = false, Grids = new ObservableCollection<GridModel> { _testGM3, _testGM4 } };
And the Button command Task :
async Task GetLotteriesAsync()
{
if (IsBusy)
return;
try
{
IsBusy = true;
_buttonCount++;
LotteriesCount = _buttonCount.ToString();
if (Lotteries.Count != 0)
Lotteries.Clear();
Lotteries.Add(_testLM1);
Lotteries.Add(_testLM2);
Lotteries.Add(_testLM1);
Lotteries.Add(_testLM2);
}
catch (Exception e)
{
Log.Error(e, "Error while trying to get our lotteries");
await Application.Current.MainPage.DisplayAlert("Error!", e.Message, "OK");
}
finally
{
IsBusy = false;
}
}
So each time I touch/click my Button, LotteriesCount string property get's updated with a static int counter field value :
static int _buttonCount = 0;
That is OK.
Now I also update this property via this CollectionChangedEventHandler :
public LotteriesVM(LotteryService lotteryService)
{
GetLotteriesCommand = new Command(async () => await GetLotteriesAsync());
Lotteries.CollectionChanged += LotteriesChangedMethod;
}
private void LotteriesChangedMethod(object sender, NotifyCollectionChangedEventArgs e)
{
LotteriesCount = _lotteriesCount + "_" + Lotteries.Count.ToString();
}
And now here the unexpected behavior : The label only update the counter part of it string property, the remaining "_1_2_3_4" added in the handler doesn't get updated in UI.
Note that I'm using a Android Pixel 5 emulator from VS 17.3 preview.
And I also noted that if I force orientation of the emulated android device, then the Label is updated !
Even more, if I force a XAML MinimalWidthRequest="200" for my Label, then it is correctly updated now !
<!-- without MinimumWidthRequest, the label update only after forcing a screen orientation-->
<Label Text="{Binding LotteriesCount}" MinimumWidthRequest="200" HorizontalOptions="Center" FontAttributes="Bold" FontSize="22" TextColor="OrangeRed"/>
So am I doing something wrong or it is a bug ? Thank you.
I am trying to capture the screen in IOS, Other than WkWebview all other view component I am able to capture by below code.WkWebview is giving a blank page as captured data. If I am using UIWebview the same code working Is there anything specific to do to take screen shot WkWebView.
Code for screen capture.
public static UIImage SnapshotView(this UIView view)
{
UIGraphics.BeginImageContextWithOptions(view.Bounds.Size, false, UIScreen.MainScreen.Scale);
view.DrawViewHierarchy(view.Bounds, true);
var image = UIGraphics.GetImageFromCurrentImageContext();
UIGraphics.EndImageContext();
return image;
}
WkWebView Configuration:
WKWebView _wkWebView = new WKWebView(ReaderView.Frame, new WKWebViewConfiguration());
_wkWebView.LoadFileUrl(tempUrl, tempUrl);
_wkWebView.ContentMode = UIViewContentMode.ScaleToFill;
_wkWebView.BackgroundColor = UIColor.Clear;
_wkWebView.Opaque = false;
_wkWebView.ScrollView.BackgroundColor = UIColor.Clear;
//_wkWebView.DrawViewHierarchy(_wkWebView.Bounds, true);
ReaderView.AddSubview(_wkWebView);
var imag = _wkWebView.SnapshotView();
I fixed the issue by replacing the WKWebView with PdfView.I am using this view for loading PDFs.
The latest code is below
pdfView = new PdfView();
pdfView.TranslatesAutoresizingMaskIntoConstraints = false;
ReaderView.AddSubview(pdfView);
pdfView.LeadingAnchor.ConstraintEqualTo(View.SafeAreaLayoutGuide.LeadingAnchor).Active = true;
pdfView.TrailingAnchor.ConstraintEqualTo(View.SafeAreaLayoutGuide.TrailingAnchor).Active = true;
pdfView.TopAnchor.ConstraintEqualTo(View.SafeAreaLayoutGuide.TopAnchor).Active = true;
pdfView.BottomAnchor.ConstraintEqualTo(View.SafeAreaLayoutGuide.BottomAnchor).Active = true;
// var path = Bundle.main.url(forResource: "test", withExtension: "pdf") else { return }
PdfDocument document;
// PdfDocument
using (urlString = new NSString(FilePath))
using (var tempUrl = NSUrl.CreateFileUrl(new string[] { urlString }))
document = new PdfDocument(tempUrl);
//if var document = PdfDocument(url: path) {
pdfView.Document = document;
There is a shadow over the CalendarDatePicker flyout. This "effect" is probably connected to the Dialog which host the control. I attached the Dialog's function. Do you know how to remove it?
Image: https://ibb.co/ZJjqfWs
private async void CreateNewDocumentDialog() {
// Creating dialoge window
var textBlock1 = new TextBlock
{
Text = "Kérem adja meg az alábbi adatokat!",
FontSize = 16
};
var docName = new TextBox
{
Name = "docName",
Margin = new Thickness(0, 10, 0, 10),
PlaceholderText = "Documentum neve"
};
var docValidUntil = new CalendarDatePicker
{
Header = "Dokumentum érvényessége:",
Date = DateTime.Now.AddYears(4),
};
var contentPanel = new StackPanel();
contentPanel.Children.Add(textBlock1);
contentPanel.Children.Add(docName);
contentPanel.Children.Add(docValidUntil);
ContentDialog CreateNewDocumentDialog = new ContentDialog
{
Content = contentPanel,
PrimaryButtonText = "Új bejegyzés létrehozása",
CloseButtonText = "Mégse",
// Default button responds to Enter
DefaultButton = ContentDialogButton.Primary
};
// Waiting for user input
ContentDialogResult result = await CreateNewDocumentDialog.ShowAsync();
if (result == ContentDialogResult.Primary)
{
// Process user input if Create New button pressed/activated
if (docName.Text != "")
{
var tempDate = docValidUntil.Date;
DocumentList.Add(new Document(docName.Text, tempDate.Value.DateTime));
}
}
else
{
// Exit dialog if Cancel button pressed
}
}
We're trying to build a Chat App using Xamarin Forms, but we keep getting this annoying bug with the Android keyboard. Whenever the "Send" button is tapped, the focus on the Entry (text box for chatting) is lost and the keyboard disappears. That isn't what we wanted so we added this line to the TapGestureRecognizer:
messageEntry.Focus();
But for some reason, this doesn't happen fast enough, and often the keyboard goes down and immediately up again. This prevents users from quickly posting multiple message sequentially. Does anybody know how this can be fixed?
Thanks to the answer of #AdamKemp in this post, here is my solution. If the touch is within my EntryStackLayout (don't forget to create the empty custom renderer), then I don't dismiss the keyboard (which is what DispatchTouchEvent will do if CurrentFocus is EditText).
public class EditorAndButtonReproPage : ContentPage
{
public EditorAndButtonReproPage()
{
BackgroundColor = Color.Gray;
Padding = 50;
var editor = new Editor {HorizontalOptions = LayoutOptions.FillAndExpand};
var editorButton = new Button {Text = "OK", HorizontalOptions = LayoutOptions.End};
var editorLayout = new EntryStackLayout { Orientation = StackOrientation.Horizontal, Children = { editor, editorButton}, VerticalOptions = LayoutOptions.Start};
var entry = new ExtendedEntry { Placeholder = "Entry", HorizontalOptions = LayoutOptions.FillAndExpand };
var entryButton = new Button { Text = "OK", HorizontalOptions = LayoutOptions.End };
var entryLayout = new EntryStackLayout { Orientation = StackOrientation.Horizontal, Children = { entry, entryButton }, VerticalOptions = LayoutOptions.Start };
Content = new StackLayout {Children = {editorLayout, entryLayout}};
}
}
and in the MainActivity:
private bool _ignoreNewFocus;
public override bool DispatchTouchEvent(MotionEvent e)
{
var currentView = CurrentFocus;
var parent = currentView?.Parent?.Parent;
var entryStackLayout = parent as EntryStackLayout;
if (entryStackLayout != null)
{
var entryLayoutLocation = new int[2];
entryStackLayout.GetLocationOnScreen(entryLayoutLocation);
var x = e.RawX + entryStackLayout.Left - entryLayoutLocation[0];
var y = e.RawY + entryStackLayout.Top - entryLayoutLocation[1];
var entryStackLayoutRect = new Rectangle(entryStackLayout.Left, entryStackLayout.Top, entryStackLayout.Width, entryStackLayout.Height);
_ignoreNewFocus = entryStackLayoutRect.Contains(x, y);
}
var result = base.DispatchTouchEvent(e);
_ignoreNewFocus = false;
return result;
}
public override Android.Views.View CurrentFocus => _ignoreNewFocus ? null : base.CurrentFocus;
It'd be a bit of a hack, but you could spin off an async task that waits 50ms and then invokes the messageEntry.Focus() line on the main UI thread...
I have a hubtile in my application which opens contacts for dialling a number. Now, i wanted to pin that into the start page of windows and i am implementing this feature by using the below code:
private void Click_Tap(object sender, RoutedEventArgs e)
{
ShellTile oTile = ShellTile.ActiveTiles.FirstOrDefault(x =>
x.NavigationUri.ToString().Contains("flip".ToString()));
if (oTile != null && oTile.NavigationUri.ToString().Contains("flip"))
{
FlipTileData oFliptile = new FlipTileData();
oFliptile.Title = "Hello WP8!!";
oFliptile.Count = 11;
oFliptile.BackTitle = "Updated Flip Tile";
oFliptile.BackContent = "back of tile";
oFliptile.WideBackContent = "back of the wide tile";
oFliptile.SmallBackgroundImage = new Uri("Assets/Tiles/Flip/h.jpg", UriKind.Relative);
oFliptile.BackgroundImage = new Uri("Assets/Tiles/Flip/h.jpg", UriKind.Relative);
oFliptile.WideBackgroundImage = new Uri("Assets/Tiles/Flip/h.jpg", UriKind.Relative);
oFliptile.BackBackgroundImage = new Uri("/Assets/Tiles/Flip/h.jpg", UriKind.Relative);
oFliptile.WideBackBackgroundImage = new Uri("/Assets/Tiles/Flip/h.jpg", UriKind.Relative);
oTile.Update(oFliptile);
MessageBox.Show("Flip Tile Data successfully update.");
}
else
{
Uri tileUri = new Uri("/phoneNumberChooserTask.show()?tile=flip", UriKind.Relative);
ShellTileData tileData = this.CreateFlipTileData();
ShellTile.Create(tileUri, tileData, true);
}
}
private ShellTileData CreateFlipTileData()
return new FlipTileData()
{
Title = "",
BackTitle = "",
BackContent = "",
WideBackContent = "",
Count = 8,
SmallBackgroundImage = new Uri("/Assets/Tiles/Flip/h.jpg", UriKind.Relative),
BackgroundImage = new Uri("/Assets/Tiles/Flip/h.jpg", UriKind.Relative),
WideBackgroundImage = new Uri("/Assets/Tiles/Flip/h.jpg", UriKind.Relative),
};
}
The problem i am facing is when i run this on a device/emulator, Tile gets pin to start but when i click the tile on the start screen of my device/emulator debugger stops the process and the process breaks.
Can anyone guide me in the right direction ?
Tile can not launch anything except your app. Add into uri some code that will be parsed by your app and then your app should call phoneNumberChooserTask.show(). For example:
new Uri("/Chooser.xaml?tile=flip", UriKind.Relative);
Then, in the Chooser.xaml (page in your project), in the OnNavigatedTo detect the title value in the Uri and call phoneNumberChooserTask.show().