ورود

View Full Version : سوال: کد دریافت کنترل ها در WPF



irartesh
پنج شنبه 28 فروردین 1393, 21:47 عصر
با سلام خدمت کاربران گرامی
یه سوال خیلی مهم و کاربردی داشتم...من چطور میتونم کنترل های های فرم رو دریافت کنم و اون هارو تو حلقه فورایچ ویرایش کنم؟؟؟؟
مثل کد زیر که در کد نویسی ویندوزفرم استفاده میشه

foreach (var item in this.Controls)
{
if (item.GetType() == typeof(TextBox))
((TextBox)item).Text = "";
}

rg_BlackRose
جمعه 29 فروردین 1393, 01:38 صبح
سلام

با فرض مثال من میخوام همه TextBox های درون StackPanel1 که در Mainwindow هست رو خالی بکنم. و کد XML مربوط به MainWindow به این صورت هست:

<Window x:Class="MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="MainWindow" Height="250" Width="325">
<Grid>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="187*" />
<ColumnDefinition Width="316*" />
</Grid.ColumnDefinitions>
<StackPanel x:Name="StackPanel1" Grid.ColumnSpan="1">
<TextBox Margin="5" />
<TextBox Margin="5" />
<TextBox Margin="5" />
<TextBox Margin="5" />
</StackPanel>

<Button x:Name="btnClearText" Grid.Column="1" Width="99" Height="33" Content="Clear Text"
Click="btnClearText_Click"/>
</Grid>


کدهای درون کلاس MainWindow به صورت زیر خواهد بود

using System;
using System.Collections.Generic;
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.Navigation;
using System.Windows.Shapes;

namespace WpfApplication1
{
/// <summary>
/// Interaction logic for MainWindow.xaml
/// </summary>
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
}

private void btnClearText_Click(object sender, RoutedEventArgs e)
{
foreach (UIElement control in StackPanel1.Children)
{
if (control.GetType() == typeof(TextBox))
{
((TextBox)control as TextBox).Text = string.Empty;
}
}
}
}
}


موفق باشید