I am trying to do this in XAML:
TextBox tb = (TextBox)e.Item.FindControl("tvNote");
I have a textbox inside of a scroll viewer and I need to find its value. Here is my code:
<Grid x:Name="itemDetailGrid" Margin="0,60,0,50">
<Grid.RowDefinitions>
<RowDefinition Height="Auto"/>
<RowDefinition Height="Auto"/>
<RowDefinition Height="Auto"/>
<RowDefinition Height="Auto"/>
</Grid.RowDefinitions>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="Auto"/>
<ColumnDefinition Width="*"/>
</Grid.ColumnDefinitions>
<Image Grid.Row="1" Margin="0,0,20,0" Width="180" Height="180" Source="{Binding Image}" Stretch="UniformToFill" AutomationProperties.Name="{Binding Title}" Visibility="Collapsed" />
<StackPanel x:Name="itemDetailTitlePanel" Grid.Row="1" Grid.Column="1">
<TextBlock x:Name="itemTitle" Margin="0,-10,0,0" Text="{Binding Name}" Style="{StaticResource SubheaderTextStyle}"/>
<TextBlock x:Name="itemSubtitle" Margin="0,0,0,20" Text="{Binding Description}" Style="{StaticResource SubtitleTextStyle}"/>
<TextBlock Grid.Row="2" Grid.ColumnSpan="2" Margin="0,20,0,0" Text="{Binding Price, Mode=TwoWay,Converter={StaticResource PriceValueConverter}}" Style="{StaticResource BodyTextStyle}"/>
<TextBox x:Name="tvQuantity"/>
<TextBox x:Name="tvNotes"/>
<Button x:Name="btnAdd" Content="Add" Click="btnAdd_Click"/>
</StackPanel>
</Grid>
</ScrollViewer>
Using a button click, how do I find TV Note? Here is my button click:
public void btnAdd_Click(object sender, RoutedEventArgs e)
{
Button btnAdd = (Button)sender;
int quan = 0;
bool q = int.TryParse(tvQuantity.Text, out quan);
if (q == false)
{
MessageDialog messageDialog = new MessageDialog("Please enter a valid quantity.", "Quantity Invalid");
messageDialog.ShowAsync();
return;
}
//this causes an issue for items in an existing order
Product product = btnAdd.CommandParameter as Product;
IEnumerable<OrderDetail> query = App.CurrentOrder.OrderDetails.Where(a => a.Name == product.Name);
if (query.Count() == 0)
{
//insert order
Repository.AddOrderDetail(product.Name, product.Description, product.Price, quan, App.CurrentOrder.Id, tvNote.Text, product.Category);
MessageDialog messageDialog = new MessageDialog(product.Name + " has been successfully added to your order.", "Item Added");
messageDialog.ShowAsync();
messageDialog.Commands.Add(new UICommand("OK", new UICommandInvokedHandler(YesCommandInvokedHandler)));
}
else
{
OrderDetail orderDetail = btnAdd.CommandParameter as OrderDetail;
orderDetail.Quantity = quan;
orderDetail.OrderDetailNote = tvNote.Text;
Repository.UpdateOrderDetail(orderDetail.Id, orderDetail.Category, orderDetail.Description, orderDetail.Name, orderDetail.OrderDetailNote, orderDetail.OrderId, orderDetail.Price, quan);
MessageDialog messageDialog = new MessageDialog(orderDetail.Name + " has been successfully updated.", "Item Updated");
messageDialog.ShowAsync();
}
I don't see tvNote in your XAML? I see:
<TextBox x:Name="tvNotes"/>
So, maybe it's a typo?
If this is in a DataTemplate, then you'll need to switch to using a different technique, as FindName won't work, as shown here.
Related
I'm creating a Wizard to export DB tables into CSV.
I'm using Xceed Wizard and I need an Event in Next button. I want to validate the parameters before going to the next page when I click "Next", but I only can set CanSelectNextPage.
XAML code:
<xctk:WizardPage x:Name="PageBD1" PageType="Interior"
Title="{DynamicResource PageBD1Title}"
Description="{DynamicResource PageBD1Desc}"
NextPage="{Binding ElementName=PageBD2}"
PreviousPage="{Binding ElementName=Page1}"
CanSelectNextPage="False">
<Grid>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="3*"/>
<ColumnDefinition Width="5*"/>
</Grid.ColumnDefinitions>
<Grid.RowDefinitions>
<RowDefinition Height="Auto"/>
<RowDefinition Height="Auto"/>
<RowDefinition Height="Auto"/>
<RowDefinition Height="Auto"/>
<RowDefinition Height="*"/>
</Grid.RowDefinitions>
<TextBlock x:Name="tbBDInfoServer1" Text="{DynamicResource tbBDInfoServer1}" Grid.Row="0" Grid.Column="0" />
<TextBox x:Name="tbBDServer1" Grid.Row="0" Grid.Column="2" TextChanged="tbBD1_TextChanged"/>
<TextBlock x:Name="tbBDInfoName1" Text="{DynamicResource tbBDInfoName1}" Grid.Row="1" Grid.Column="0" Margin="0,10,0,0" />
<TextBox x:Name="tbBDName1" Grid.Row="1" Grid.Column="2" Margin="0,10,0,0" TextChanged="tbBD1_TextChanged"/>
<TextBlock x:Name="tbBDInfoUser1" Text="{DynamicResource tbBDInfoUser1}" Grid.Row="2" Grid.Column="0" Margin="0,10,0,0" />
<TextBox x:Name="tbBDUser1" Grid.Row="2" Grid.Column="2" Margin="0,10,0,0" TextChanged="tbBD1_TextChanged"/>
<TextBlock x:Name="tbBDInfoPwd1" Text="{DynamicResource tbBDInfoPwd1}" Grid.Row="3" Grid.Column="0" Margin="0,10,0,0" />
<PasswordBox x:Name="tbBDPwd1" Grid.Row="3" Grid.Column="2" Margin="0,10,0,0"/>
</Grid>
</xctk:WizardPage>
C# code:
private void tbBD1_TextChanged(object sender, TextChangedEventArgs e)
{
if (tbBDServer1.Text != "" && tbBDName1.Text != "" && tbBDUser1.Text != "")
{
PageBD1.CanSelectNextPage = true;
}
else
PageBD1.CanSelectNextPage = false;
}
Thanks.
At the past, I can convert and save an usercontrol to an JPEG image with this code:
private string CreateBitmapImage(FrameworkElement usefulData, string name) // Tekli görev kartını masaüstünde oluşturmak için, resim yaratma fonksiyonu.
{
try
{
string fullFileName = string.Empty;
Size size = new Size(642, 416);
usefulData.Measure(size);
usefulData.Arrange(new Rect(size));
var rtb = new RenderTargetBitmap((int)usefulData.ActualWidth, (int)usefulData.ActualHeight, 96, 96, PixelFormats.Pbgra32);
rtb.Render(usefulData);
var encoder = new JpegBitmapEncoder();
encoder.Frames.Add(BitmapFrame.Create(rtb));
SaveFileDialog dlg = new SaveFileDialog();
dlg.Title = "Görev kartını nereye kaydetmek istersiniz ?";
dlg.FileName = name; // Default file name
dlg.DefaultExt = ".jpg"; // Default file extension
dlg.Filter = "Resim Dosyası (.jpg)|*.jpg"; // Filter files by extension
dlg.OverwritePrompt = true;
var result = dlg.ShowDialog();
if (result == true && dlg.CheckPathExists == true)
{
fullFileName = System.IO.Path.Combine(dlg.FileName);
using (var filestream = new FileStream(fullFileName, FileMode.Create))
{
encoder.Save(filestream);
}
}
return fullFileName;
}
catch
{
MessageBox.Show("Tek görev kartını yaratırken bir hata oluştu.Lütfen yeniden deneyin.", "Hata", MessageBoxButton.OK, MessageBoxImage.Error);
return "";
}
}
Now, I'm converting my WPF project to UWP. However, I cannot find how I convert and save an usercontrol to an Jpeg image in UWP. Can you help me please ?
Thanks.
Update: My UserControl in UWP. As I explained at bottom, I got an exception if I try render the user control:
<UserControl
x:Class="AYOS_IDPrinter_UWP.TaskCard"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="using:AYOS_IDPrinter_UWP"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
mc:Ignorable="d"
d:DesignHeight="416"
d:DesignWidth="642" HorizontalAlignment="Center" VerticalAlignment="Center" RequestedTheme="Default">
<UserControl.Resources>
<SolidColorBrush x:Key="AuSupportColor" Color="#FFE5C97C"/>
</UserControl.Resources>
<Border x:Name="OutSketch" BorderThickness="2" BorderBrush="{StaticResource AuSupportColor}">
<Grid x:Name="MainGrid" Background="White">
<Grid.RowDefinitions>
<RowDefinition Height="30"/>
<RowDefinition Height="*"/>
</Grid.RowDefinitions>
<Border x:Name="NeedleArea" BorderThickness="0,0,0,2" Background="{StaticResource AUColor}" BorderBrush="{StaticResource AuSupportColor}">
<TextBlock x:Name="Label" TextWrapping="Wrap" Text="İğne Alanı / Needle Area" Foreground="White" TextAlignment="Center" Margin="0" VerticalAlignment="Center" FontFamily="Noto Sans" FontWeight="Normal"/>
</Border>
<Grid x:Name="Values" HorizontalAlignment="Stretch" Margin="10,10,10,10" VerticalAlignment="Stretch" Grid.Row="2">
<Grid.RowDefinitions>
<RowDefinition Height="*"/>
<RowDefinition Height="*"/>
<RowDefinition Height="*"/>
</Grid.RowDefinitions>
<Grid x:Name="Header" Margin="0">
<Grid.RowDefinitions>
<RowDefinition Height="Auto"/>
<RowDefinition Height="Auto"/>
<RowDefinition Height="Auto"/>
<RowDefinition Height="Auto"/>
</Grid.RowDefinitions>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="128"/>
<ColumnDefinition/>
<ColumnDefinition Width="128"/>
</Grid.ColumnDefinitions>
<Image x:Name="Logo1" Source="Images/AULogo.png" Margin="0" Grid.RowSpan="4" HorizontalAlignment="Center" VerticalAlignment="Center" Width="100" Height="100"/>
<Image x:Name="Logo2" Source="Images/AnkudemLogo.png" Margin="0" Grid.RowSpan="4" Grid.Column="2" HorizontalAlignment="Center" VerticalAlignment="Center" Width="100" Height="100"/>
<TextBlock x:Name="Header_1" Grid.Column="1" Margin="0" TextWrapping="Wrap" Text="AYÖS" FontSize="28" TextAlignment="Center" FontWeight="Bold" Foreground="#FF284985" FontFamily="Noto Sans"/>
<TextBlock x:Name="Header_2" Grid.Column="1" Margin="0" TextWrapping="Wrap" Text="SINAV GÖREV KARTI" FontSize="24" TextAlignment="Center" Grid.Row="1" Foreground="#FF284985" FontFamily="Noto Sans"/>
<TextBlock x:Name="Header_3" Grid.Column="1" Margin="0" TextWrapping="Wrap" Text="EXAMINATION TASK CARD" FontSize="24" TextAlignment="Center" Grid.Row="2" Foreground="#FF284985" FontFamily="Noto Sans"/>
<TextBlock x:Name="DateText" Grid.Column="1" Margin="0" TextWrapping="Wrap" FontSize="22" TextAlignment="Center" Grid.Row="3" Foreground="#FF284985" Text="28 Mayıs 2016 – May 28, 2016" FontFamily="Noto Sans"/>
</Grid>
<Grid x:Name="Data" Grid.Row="1" Margin="0,18,0,-17">
<Grid.RowDefinitions>
<RowDefinition Height="Auto"/>
<RowDefinition Height="Auto"/>
</Grid.RowDefinitions>
<TextBlock x:Name="NameText" Margin="0,10,0,0" TextWrapping="Wrap" FontSize="32" TextAlignment="Center" Foreground="Red" Text="BERK BABADOĞAN" FontWeight="Bold" FontFamily="Noto Sans"/>
<TextBlock x:Name="TaskText" Margin="0,0,0,10" TextWrapping="Wrap" Text="Salon Başkanı" FontSize="28" TextAlignment="Center" Foreground="Black" Grid.Row="1" FontFamily="Noto Sans"/>
</Grid>
<Grid x:Name="Specs" Margin="10" Grid.Row="2">
<Grid.ColumnDefinitions>
<ColumnDefinition Width="Auto"/>
<ColumnDefinition Width="Auto"/>
</Grid.ColumnDefinitions>
<Grid.RowDefinitions>
<RowDefinition Height="Auto"/>
<RowDefinition Height="Auto"/>
<RowDefinition Height="Auto"/>
</Grid.RowDefinitions>
<TextBlock x:Name="SpecsH_1" Margin="0,0,5,0" TextWrapping="Wrap" Text="Sınav Yeri / Exam Area: " FontSize="20" Foreground="#FF343434" FontStyle="Italic" FontWeight="Bold" VerticalAlignment="Center" FontFamily="Noto Sans"/>
<TextBlock x:Name="SpecsH_2" Margin="0,0,5,0" TextWrapping="Wrap" Text="Salon Adı / Hall Name:" FontSize="20" Foreground="#FF343434" Grid.Row="1" FontStyle="Italic" FontWeight="Bold" VerticalAlignment="Center" FontFamily="Noto Sans"/>
<TextBlock x:Name="SpecsH_3" Margin="0,0,5,0" TextWrapping="Wrap" Text="Salon No / Hall Number:" FontSize="20" Foreground="#FF343434" Grid.Row="2" FontStyle="Italic" FontWeight="Bold" VerticalAlignment="Center" FontFamily="Noto Sans"/>
<TextBlock x:Name="AreaText" Margin="5,0,0,0" TextWrapping="Wrap" Text="İstanbul" FontSize="20" Foreground="#FF343434" FontStyle="Italic" Grid.Column="1" VerticalAlignment="Center" FontFamily="Noto Sans"/>
<TextBlock x:Name="HallNameText" Margin="5,0,0,0" TextWrapping="Wrap" Text="A Blok 3. Kat Derslik 316" FontSize="20" Foreground="#FF343434" Grid.Row="1" FontStyle="Italic" Grid.Column="1" VerticalAlignment="Center" FontFamily="Noto Sans"/>
<TextBlock x:Name="HallNoText" Margin="5,0,0,0" TextWrapping="Wrap" Text="340111" FontSize="20" Foreground="#FF343434" Grid.Row="2" FontStyle="Italic" Grid.Column="1" VerticalAlignment="Center" FontFamily="Noto Sans"/>
</Grid>
</Grid>
</Grid>
</Border>
It is the code how I create an instance from my user control:
var item = new TaskCard(Name_TextBox.Text.ToUpper() + " " + Surname_TextBox.Text.ToUpper(), Task_TextBox.Text, ExamArea_TextBox.Text, HallName_TextBox.Text,HallNumber_TextBox.Text,DateConverter.Get(Date_Picker.Date.ToString())); // Creating card.
RenderTargetBitmap renderTargetBitmap = new RenderTargetBitmap();
await renderTargetBitmap.RenderAsync(item); // Gives error here.
var pixelBuffer = await renderTargetBitmap.GetPixelsAsync();
For converting, UWP app also has RenderTargetBitmap class for capturing a UIElement as an image source. For file saving, you could reference this turtorial. In UWP app we have FileSavePicker which is similar to SaveFileDialog. For example, a completed demo as follows:
RenderTargetBitmap renderTargetBitmap = new RenderTargetBitmap();
await renderTargetBitmap.RenderAsync(elementToRender, 642,416);
var pixelBuffer = await renderTargetBitmap.GetPixelsAsync();
var savePicker = new FileSavePicker();
savePicker.DefaultFileExtension = ".png";
savePicker.FileTypeChoices.Add(".png", new List<string> { ".png" });
savePicker.SuggestedStartLocation = PickerLocationId.PicturesLibrary;
savePicker.SuggestedFileName = "snapshot.png";
// Prompt the user to select a file
var saveFile = await savePicker.PickSaveFileAsync();
// Verify the user selected a file
if (saveFile == null)
return;
// Encode the image to the selected file on disk
using (var fileStream = await saveFile.OpenAsync(FileAccessMode.ReadWrite))
{
var encoder = await BitmapEncoder.CreateAsync(BitmapEncoder.PngEncoderId, fileStream);
encoder.SetPixelData(
BitmapPixelFormat.Bgra8,
BitmapAlphaMode.Ignore,
(uint)renderTargetBitmap.PixelWidth,
(uint)renderTargetBitmap.PixelHeight,
DisplayInformation.GetForCurrentView().LogicalDpi,
DisplayInformation.GetForCurrentView().LogicalDpi,
pixelBuffer.ToArray());
await encoder.FlushAsync();
}
More details you could reference the official XAML render to bitmap sample.
Update:
Also add the XAML code section which use a UserControl for testing. What pass to the RenderAsync method should be the name of the Element you want to render.
<local:MyUserControl
x:Name="elementToRender"
Width="100"
Height="150" />
I did some researches why I can't render a TargetBitmap from code. I found a reason at this link:
You cannot save visual element which in code (offscreen) to image.
So, I foluna a new way to render my code based user control. I created my user control via code like this:
//Initializing task card.
var item = new TaskCard(Name_TextBox.Text.ToUpper() + " " + Surname_TextBox.Text.ToUpper(), Task_TextBox.Text, ExamArea_TextBox.Text, HallName_TextBox.Text, HallNumber_TextBox.Text, DateConverter.Get(Date_Picker.Date.ToString())); // Creating card.
After this, I added a custom popup-like element with this:
<Border x:Name="RingBorder" Margin="0,0,0,0" HorizontalAlignment="Center" VerticalAlignment="Center" BorderBrush="{ThemeResource SystemControlBackgroundBaseHighRevealBorderBrush}" BorderThickness="2,2,2,2" RequestedTheme="Default" Visibility="Collapsed" >
<Grid x:Name="InnerGrid_Ring" Background="{ThemeResource ApplicationPageBackgroundThemeBrush}" RequestedTheme="Default" HorizontalAlignment="Stretch" VerticalAlignment="Stretch">
<Grid.RowDefinitions>
<RowDefinition Height="auto"/>
<RowDefinition Height="auto"/>
</Grid.RowDefinitions>
<Grid x:Name="WaiterRing_SecondRow" HorizontalAlignment="Stretch" Margin="0,0,0,0" VerticalAlignment="Stretch" Grid.Row="2">
<Grid.ColumnDefinitions>
<ColumnDefinition Width="Auto"></ColumnDefinition>
<ColumnDefinition Width="Auto"></ColumnDefinition>
</Grid.ColumnDefinitions>
<TextBlock x:Name="LoadValue_Ring" Text="Lütfen bekleyin..." TextWrapping="Wrap" FontWeight="Normal" Margin="10,0,10,0" TextAlignment="Center" VerticalAlignment="Center" HorizontalAlignment="Stretch" Grid.Column="1" Style="{StaticResource TitleTextBlockStyle}" />
<ProgressRing x:Name="Waiter_Ring" HorizontalAlignment="Center" Margin="10,10,10,10" VerticalAlignment="Center" Foreground="{StaticResource AndroidGreen}" IsActive="True" Width="40" Height="40"/>
</Grid>
<Grid x:Name="CardViewerGrid_Ring" HorizontalAlignment="Center" Height="416" Margin="0,0,0,0" VerticalAlignment="Center" Width="642"/>
</Grid>
</Border>
Lastly, I'm rendering the user control like this:
//Converting UIelement to Rendered Bitmap
CardViewerGrid_Ring.Children.Add(item); // Adding card to canvas.
RenderTargetBitmap renderTargetBitmap = new RenderTargetBitmap();
await renderTargetBitmap.RenderAsync(CardViewerGrid_Ring); // Render canvas.
var pixelBuffer = await renderTargetBitmap.GetPixelsAsync();
And, voila :)
I have json as below:
I want to display the data in the gallery on the gridview, then if the user clicks the image on the gridview, it will show a picture with a larger size on the flipview according to the selected image. I'm having trouble, that is when the image on the gridview is selected, it always shows up the image on the flipview for the first index (not in accordance with the picture chosen by the user).
XAML:
<callisto:CustomDialog x:FieldModifier="public" x:Name="ArticleDetail"
Grid.Row="0" Grid.RowSpan="2" Title=""
Background="White" BackButtonVisibility="Collapsed" BorderBrush="White" >
<ScrollViewer Margin="0,0,5,5" Background="{x:Null}" VerticalScrollBarVisibility="Auto" HorizontalScrollMode="Disabled">
<StackPanel Height="auto">
<ProgressRing x:Name="articleDetailLoading" HorizontalAlignment="Center" VerticalAlignment="Center" Height="50" Width="50" />
<StackPanel x:Name="articleDetailBox" Margin="0,0,10,10" Height="auto">
<Grid x:Name="articleDetailGrid" BorderBrush="#FF990000" BorderThickness="1">
<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>
<TextBlock x:Name="articleIdDetail" Grid.Row="0" Text="{Binding ID}" Visibility="Collapsed"/>
<AppBarButton x:Name="closeArticleBtn" Icon="Clear" HorizontalAlignment="Right" Foreground="Black" Click="closeArticleBtn_Click"/>
<ScrollViewer x:Name="articleTitleScroll" Grid.Row="1" Margin="10,0,0,0" Width="650" Height="50" VerticalAlignment="Top" HorizontalAlignment="Left" VerticalScrollBarVisibility="Auto" Background="{x:Null}" HorizontalScrollMode="Disabled">
<TextBlock x:Name="articleTitleDetail" Margin="0,0,15,15" FontSize="18" FontFamily="Segoe UI Black" FontWeight="SemiBold" TextWrapping="Wrap" Height="auto" TextAlignment="Center"/>
</ScrollViewer>
<TextBlock x:Name="articleDateDetail" Grid.Row="3" Margin="10,15,10,0" FontSize="15" FontFamily="Segoe UI Black" FontWeight="SemiLight" TextWrapping="Wrap" Height="auto" TextAlignment="Center"/>
<GridView x:Name="articleImageGridView" Grid.Row="5" Margin="10,25,10,0" Height="110" AutomationProperties.AutomationId="ItemDetailScrollViewer" DataContext="{Binding SelectedItem, ElementName=itemListView}"
ScrollViewer.HorizontalScrollMode="Auto" ScrollViewer.VerticalScrollMode="Auto" IsItemClickEnabled="True"
ScrollViewer.ZoomMode="Disabled" ScrollViewer.VerticalScrollBarVisibility="Disabled" ScrollViewer.HorizontalScrollBarVisibility="Auto" ItemClick="articleImageGridView_ItemClick">
<GridView.ItemTemplate>
<DataTemplate>
<Grid Height="90" Width="120" Margin="5,0,0,0" Background="{x:Null}" BorderBrush="#FF646464" BorderThickness="0.5">
<Border x:Name="coverBox" Grid.Row="0" Margin="0,0,0,0" Width="120" Height="90" VerticalAlignment="Top" HorizontalAlignment="Left" BorderBrush="Black" BorderThickness="0.5">
<Border.Background>
<ImageBrush Stretch="UniformToFill" ImageSource="images/IP-placeholder.png"/>
</Border.Background>
<Image x:Name="cover" Source="{Binding ImageURL1}" HorizontalAlignment="Center" Stretch="Uniform" AutomationProperties.Name="{Binding Title}" ImageOpened="Image_ImageOpened" Loaded="cover_Loaded" Loading="cover_Loading"/>
</Border>
</Grid>
</DataTemplate>
</GridView.ItemTemplate>
<GridView.ItemsPanel>
<ItemsPanelTemplate>
<ItemsWrapGrid Orientation="Vertical" />
</ItemsPanelTemplate>
</GridView.ItemsPanel>
</GridView>
<WebView x:Name="articleContentDetail" Grid.Row="6" Margin="10,15,10,10" Width="650" Height="150" VerticalAlignment="Top" HorizontalAlignment="Left"/>
</Grid>
</StackPanel>
<StackPanel x:Name="articleFullImageDetailBox" Margin="0,0,10,10" Height="auto" Visibility="Collapsed">
<Grid x:Name="articleFullImageDetailGrid" BorderBrush="#FF990000" BorderThickness="1">
<Grid.RowDefinitions>
<RowDefinition Height="auto"/>
<RowDefinition Height="*"/>
</Grid.RowDefinitions>
<AppBarButton x:Name="closearticleFullImageBtn" Grid.Column="1" Icon="Clear" HorizontalAlignment="Right" Foreground="Black" Click="closearticleFullImageBtn_Click"/>
<TextBlock x:Name="articleFullIdDetail" Grid.Row="0" Text="{Binding ID}" Visibility="Collapsed"/>
<FlipView x:Name="articleImageFullFlipview" Grid.Row="1" Grid.RowSpan="3" Grid.Column="0" Margin="0,0,0,0" ItemsSource="{Binding gallery.Items}" SelectedItem="{Binding gallery, Mode=TwoWay}" Width="650" Height="500" VerticalAlignment="Center" HorizontalAlignment="Left" BorderBrush="Black" BorderThickness="1" Background="{x:Null}">
<FlipView.ItemTemplate>
<DataTemplate>
<Grid x:Name="content" Margin="0,0,0,0">
<Border x:Name="coverBox" Width="600" Height="500">
<Border.Background>
<ImageBrush Stretch="Uniform" ImageSource="images/IP-placeholder.png"/>
</Border.Background>
<Image x:Name="cover" Source="{Binding ImageURLFull}" HorizontalAlignment="Center" Stretch="UniformToFill" AutomationProperties.Name="{Binding ID}" ImageOpened="Image_ImageOpened" Loaded="cover_Loaded" Loading="cover_Loading"/>
</Border>
</Grid>
</DataTemplate>
</FlipView.ItemTemplate>
</FlipView>
</Grid>
</StackPanel>
</StackPanel>
</ScrollViewer>
</callisto:CustomDialog>
Code:
ObservableCollection<ArticleClass> articleDatasourceDetailImage = new ObservableCollection<ArticleClass>();
articleDatasourceDetailImage.Clear();
articleDetailLoading.Visibility = Visibility.Visible;
articleDetailLoading.IsActive = true;
articleDetailBox.Visibility = Visibility.Collapsed;
articleFullImageDetailBox.Visibility = Visibility.Collapsed;
ArticleDetail.IsOpen = true;
articleItemDetail = e.ClickedItem as ArticleClass;
articleIdDetail.Text = articleItemDetail.ID.ToString();
ConnectionProfile connections = NetworkInformation.GetInternetConnectionProfile();
if (connections != null && connections.GetNetworkConnectivityLevel() == NetworkConnectivityLevel.InternetAccess)
{
articleDetailLoading.IsActive = true;
try
{
string urlPath = "http://indonesia-product.com/api/v1/articles/"10.json?module=articles&page=1&token=3f63-dc43-c8d5-eb45-8cbf-b72d-9d98-800f";
//Debug.WriteLine(urlPath.ToString());
var httpClient = new HttpClient(new HttpClientHandler());
var values = new List<KeyValuePair<string, string>>
{
};
HttpResponseMessage response = await httpClient.GetAsync(urlPath);
response.EnsureSuccessStatusCode();
if (!response.IsSuccessStatusCode)
{
articleDetailLoading.IsActive = false;
RequestException();
}
string jsonText = await response.Content.ReadAsStringAsync();
JsonObject jsonObject = JsonObject.Parse(jsonText);
JsonObject jsonData = jsonObject["data"].GetObject();
JsonObject groupObject1 = jsonData.GetObject();
double id = groupObject1["id"].GetNumber();
string title = groupObject1["title"].GetString();
string date = groupObject1["publication_date"].GetString();
JsonArray jsonGallery = groupObject1["gallery"].GetArray();
foreach (JsonValue groupValue1 in jsonGallery)
{
JsonObject groupObject2 = groupValue1.GetObject();
string imageUrl = groupObject2.ContainsKey("image_url") && groupObject2["image_url"] != null ? groupObject2["image_url"].GetString() : string.Empty;
ArticleClass fileImage = new ArticleClass();
fileImage.ImageURL1 = imageUrl;
articleDatasourceDetailImage.Add(fileImage);
}
articleImageGridView.ItemsSource = articleDatasourceDetailImage;
articleDetailLoading.IsActive = false;
ArticleClass file = new ArticleClass();
file.ID = Convert.ToInt32(id);
file.Title = title;
DateTime dateConvert = Convert.ToDateTime(date);
file.Date = dateConvert.ToString("MMM d, yyyy");
articleContentDetail.NavigateToString(contentText);
articleDetailLoading.IsActive = false;
articleDetailBox.Visibility = Visibility.Visible;
articleDetailLoading.Visibility = Visibility.Collapsed;
articleDetailLoading.IsActive = false;
}
catch (HttpRequestException ex)
{
articleDetailLoading.IsActive = false;
}
}
else
{
articleDetailLoading.IsActive = false;
}
}
private async void articleImageGridView_ItemClick(object sender, ItemClickEventArgs e)
{
articleDetailLoading.Visibility = Visibility.Visible;
articleDetailLoading.IsActive = true;
articleDetailBox.Visibility = Visibility.Collapsed;
articleFullImageDetailBox.Visibility = Visibility.Collapsed;
var articleImageGridView = (GridView)sender;
articleImageFullFlipview.SelectedIndex = articleImageGridView.SelectedIndex;
articleFullImageDetailBox.Visibility = Visibility.Visible;
articleDetailLoading.Visibility = Visibility.Collapsed;
articleDetailLoading.IsActive = false;
}
How to handle it?
First, there is no need to get your data again when clicking on the item. When you load your data, set the ItemsSource of your GridView and your FlipView to be the same collection.
Second, when your item is clicked, get the SelectedIndex of the item and then set the SelectedIndex of your FlipView
private async Task LoadData()
{
// get data
var response = await httpClient.GetAsync(url);
// Convert to your objects
articleImageFullFlipview.ItemsSource = data;
articleImageGridView.ItemsSource = data;
}
private void articleImageGridView_ItemClick(object sender, ItemClickEventArgs e)
{
var gridView = (GridView)sender;
articleImageFullFlipview.SelectedIndex = gridView.SelectedIndex;
// show or hide any controls
}
My problem is that my items won't add to the list. I try to add 3 texts and one image location to the list. I try everything but I couldn't do it.
XAML code
<ListBox Name="mylistbox" Grid.Row="0" Grid.Column="0" Grid.ColumnSpan="6" Grid.RowSpan="3">
<ListBox.ItemTemplate>
<DataTemplate>
<StackPanel Name="s1">
<Grid>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="10"/>
<ColumnDefinition Width="120"/>
<ColumnDefinition Width="300"/>
<ColumnDefinition Width="10"/>
</Grid.ColumnDefinitions>
<Grid.RowDefinitions>
<RowDefinition Height="10"/>
<RowDefinition Height="100"/>
<RowDefinition Height="30"/>
<RowDefinition Height="20/"/>
</Grid.RowDefinitions>
<TextBlock Text="{Binding naslov}" Tag="{Binding broj}" FontSize="32" Foreground="White" HorizontalAlignment="Center" TextWrapping="Wrap" Grid.Row="1" Grid.Column="2" />
<TextBlock Text="{Binding datum}" Foreground="White" HorizontalAlignment="Right" VerticalAlignment="Center" TextWrapping="Wrap" Grid.Row="2" Grid.Column="2"/>
<Image Source="{Binding slika}" Grid.Row="1" Grid.Column="1" Grid.RowSpan="2"/>
</Grid>
</StackPanel>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
C# code
for (int i = 1; i < datum.Count; ++i)
{
podatak _podatak = new podatak();
_podatak.naslov = naslovi[i];
_podatak.datum = datum[i];
_podatak.broj = Convert.ToString(broj);
_podatak.slika = "http://hsin.hr/images/logo.gif";
mylistbox.Items.Add(_podatak);
}
I didn't test, but I think you are missing one detail, and doing a little mistake.
First: you need to bind a List to a ListBox. So, I believe you should do something like this:
List<podatak> myList = new List<podatak>();
for (int i = 1; i < datum.Count; ++i)
{
podatak _podatak = new podatak();
_podatak.naslov = naslovi[i];
_podatak.datum = datum[i];
_podatak.broj = Convert.ToString(broj);
_podatak.slika = "http://hsin.hr/images/logo.gif";
myList.Add(_podatak);
}
mylistbox.ItemsSource = myList;
And Second: add this on xaml:
<ListBox Name="mylistbox" ItemsSource="{Binding}" ...
Correcting:
As commented, doesn't need change anything on your XAML code.
My mistake.
I created a class "MyPolygonClass" from which I created an instance that I have databound to the User Control.
This works fine.
However, if the user changes the number of polygon sides I would like to update a canvas, also shown in the User Contol - but not part of MyPolygonClass
I initially run UpdateCanvas(), but it doesn't update if _poly is updated. How do I call UpdateCanvas() everytime _poly is changed?
public partial class MainWindow : Window
{
private MyPolygonClass _poly;
public MainWindow()
{
InitializeComponent();
}
public void UpdateCanvas()
{
//Create a canvas
Canvas drawingCanvas = GenerateCanvas(this._poly.CornerCount);
//Overwrite the existing Canvas
var vb = drawingPlaceholder.Parent as Viewbox;
if (vb != null)
{
vb.Child = drawingCanvas;
}
}
private void Window_Loaded(object sender, RoutedEventArgs e)
{
BackgroundWorker worker = new BackgroundWorker();
worker.RunWorkerCompleted += worker_RunWorkerCompleted;
worker.DoWork += worker_DoWork;
worker.RunWorkerAsync();
}
void worker_DoWork(object sender, DoWorkEventArgs e)
{
//Gets the Info from a Database
this._poly = DataSupplier.GetPolygon();
}
void worker_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
{
//Do Databinding Here
Menu.DataContext = this._poly;
// Display
UpdateCanvas();
}
}
XAML:
<Grid.Resources>
<DataTemplate x:Key="LegTemplate">
<Grid>
<Grid.RowDefinitions>
<RowDefinition Height="20"></RowDefinition>
<RowDefinition Height="5"></RowDefinition>
</Grid.RowDefinitions>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="1*"></ColumnDefinition>
<ColumnDefinition Width="2*"></ColumnDefinition>
<ColumnDefinition Width="2*"></ColumnDefinition>
<ColumnDefinition Width="3*"></ColumnDefinition>
</Grid.ColumnDefinitions>
<Viewbox Grid.Row="0" Grid.Column="0" >
<Label Name="IdLabel" Content="{Binding Path=Name}"/>
</Viewbox>
<WrapPanel Grid.Row="0" Grid.Column="3">
<Button FontFamily="Marlett" Name="ButtonUp" Content="5" Click="Button_Click_Move_Leg_Up" Style="{StaticResource LegButtonUp}"></Button>
<Button FontFamily="Marlett" Name="ButtonDown" Content="6" Click="Button_Click_Move_Leg_Down" Style="{StaticResource LegButtonDown}"></Button>
<Button Name="ButtonDelete" Content="x" Click="Button_Click_Delete_Leg" Style="{StaticResource LegButtonDel}"></Button>
</WrapPanel>
<TextBox Grid.Row="0" Grid.Column="1" Name="TextBoxLength" Text="{Binding Path=Length, Converter={StaticResource DoubleConverter}, ConverterCulture=de-de, Mode=TwoWay, StringFormat=N1}" TextAlignment="Right"/>
<TextBox Grid.Row="0" Grid.Column="2" Name="TextBoxAngle" Text="{Binding Path=Angle, Converter={StaticResource DoubleConverter}, ConverterCulture=de-de, Mode=TwoWay, StringFormat=N1}" TextAlignment="Right"/>
</Grid>
</DataTemplate>
XAML2:
<StackPanel>
<Grid>
<Grid.RowDefinitions>
<RowDefinition></RowDefinition>
<RowDefinition Height="5"></RowDefinition>
</Grid.RowDefinitions>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="1*"></ColumnDefinition>
<ColumnDefinition Width="2*"></ColumnDefinition>
<ColumnDefinition Width="2*"></ColumnDefinition>
<ColumnDefinition Width="3*"></ColumnDefinition>
</Grid.ColumnDefinitions>
<Label Grid.Row="0" Grid.Column="1" HorizontalAlignment="Right">Length</Label>
<Label Grid.Row="0" Grid.Column="2" HorizontalAlignment="Right">Angle</Label>
</Grid>
<ItemsControl x:Name="LbLegs" ItemTemplate="{DynamicResource LegTemplate}" />
<Button Content="AddLeg" Click="Button_Click_2"></Button>