1

私はWPF、特に検証とデータバインディングを始めたばかりです。

これは私の XAML コードです

<Window x:Class="simpledatagrid.MainWindow"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    Title="IDDATA" Height="350" Width="525">
<Grid  >
    <DataGrid SelectionChanged="Iddetails" Name="dgsample" BorderBrush="Black" BorderThickness="2" AutoGenerateColumns="True" CanUserAddRows="True" CanUserDeleteRows="True" CanUserSortColumns="False"  Margin="200,10,10,75"></DataGrid>

    <Label  Content="ID :" HorizontalAlignment="Left" Margin="10,10,0,0" VerticalAlignment="Top" Height="26" Width="27"/>
    <Label  Content="Name :" HorizontalAlignment="Left" Margin="10,60,0,0" VerticalAlignment="Top" Height="26" Width="48"/>
    <Label  Content="Salary :" HorizontalAlignment="Left" Margin="10,110,0,0" VerticalAlignment="Top" Height="26" Width="47"/>

    <TextBox Name="tb1" HorizontalAlignment="Left" Height="20" Margin="60,10,0,0" TextWrapping="NoWrap" Text="" VerticalAlignment="Top" Width="100" />
    <TextBox Name="tb2" HorizontalAlignment="Left" Height="20" Margin="60,60,0,0" TextWrapping="NoWrap" Text="" VerticalAlignment="Top" Width="100"/>
    <TextBox Name="tb3" HorizontalAlignment="Left" Height="20" Margin="60,110,0,0" TextWrapping="NoWrap" Text="" VerticalAlignment="Top" Width="100"/>

    <Button Content="Get" HorizontalAlignment="Left" Margin="10,190,0,0" VerticalAlignment="Top" Width="75" Click="Get_Click" />
    <Button Content="Add" HorizontalAlignment="Left" Margin="10,230,0,0" VerticalAlignment="Top" Width="75" Click="Add_Click" />
    <Button Content="Delete" HorizontalAlignment="Left" Margin="10,270,0,0" VerticalAlignment="Top" Width="75" Click="Delete_Click" />
</Grid>

これは私の .CS コードです

public partial class MainWindow : Window
{
    ObservableCollection<User> Users = new ObservableCollection<User>();
    public MainWindow()
    {
        InitializeComponent();

                    Users.Add(new User() { Id = 101, Name = "leon", Salary = 10 });
                    Users.Add(new User() { Id = 102, Name = "allen", Salary = 20 });
                    Users.Add(new User() { Id = 103, Name = "neon", Salary = 30 });
                    Users.Add(new User() { Id = 104, Name = "xeln", Salary = 40 });
                    Users.Add(new User() { Id = 105, Name = "kalen", Salary = 50 });
                    Users.Add(new User() { Id = 106, Name = "velen", Salary = 60 });

                    dgsample.ItemsSource = Users;

            }

   private void Iddetails(object sender, SelectionChangedEventArgs args)
    {
        int index = dgsample.SelectedIndex;

        tb1.Text = Users[index].Id.ToString();
        tb2.Text = Users[index].Name;
        tb3.Text = Users[index].Salary.ToString();

    }
    private void Get_Click(object sender, RoutedEventArgs e)
    {


        int index;
        if (int.TryParse(this.tb1.Text, out index))
        {
            User currentUser = Users.FirstOrDefault(Select => Select.Id == int.Parse(tb1.Text));
            if (currentUser != null)
            {
                this.tb2.Text = currentUser.Name;
                this.tb3.Text = currentUser.Salary.ToString();
            }
            else
                MessageBox.Show("User with the provided ID does not Exist", "Error");
        }
        else
            MessageBox.Show("ID entered is not valid number", "Error");





        }



    private void Add_Click(object sender, RoutedEventArgs e)
    {


        if (!tb1.Text.Equals(""))

        {
            var adduser = Users.Where(User => User.Id == int.Parse(tb1.Text));

            if (!adduser.Any())
            {
                Users.Add(new User() { Id = int.Parse(tb1.Text), Name = tb2.Text, Salary = int.Parse(tb3.Text) });
            }

            else

                MessageBox.Show("Someone already has that ID.");

        }

    }

    private void Delete_Click(object sender, RoutedEventArgs e)
    {
        int index;
        if (int.TryParse(this.tb1.Text, out index))
        {
            User currentUser = Users.FirstOrDefault(Select => Select.Id == int.Parse(tb1.Text));
            if (currentUser != null)
            {
                Users.Remove(currentUser);
            }
            else
                MessageBox.Show("User with the provided ID does not Exist", "Error");
        }
        else
            MessageBox.Show("ID entered is not valid number", "Error");

    }

    }

このコードは機能していますが、DataBinding と TextBox の検証の概念を使用して同じことが必要です。必要なコードを教えてください

4

3 に答える 3

1

たとえば、データ バインディングの作成に関する一般的な概要である DataBinding を使用して、いくつかの作業を書き直す必要があります。

<TextBox Name="tb3" HorizontalAlignmentText="{Binding Path=SelectedIndex, ElementName=Grid, , Mode=OneWay}"/>

つまり、次のモードを使用してTextTextBoxのプロパティを要素tb3の次のプロパティにバインドしました。つまり、グリッドで選択されたインデックスを変更すると tb3 に影響しますが、テキストボックスで を変更しても実際の選択には影響しません。プロパティの型が一致しない場合、コンバーターを使用する必要がある場合があります。次に例を示します。SelctedIndexGridOneWayTextTextGrid

msdn.microsoft.com

一般的にはこのように見えますが、コード ビハインドでプロパティをバインドすることもできますが、xaml にとどまることができる場合は注意してください。

ヒント: バインディングを使用する場合はPath、プロパティがポイントされていることを確認する必要があります。

最後に、確認する必要がある検証の詳細については、次のリンクを参照してください。

新規: www.codeproject.com

そう質問

blogs.msdn.com

または分離コード (非推奨)

private void tb1_TextChanged(object sender, TextChangedEventArgs e)
{
    int output;
    if (!int.TryParse(tb1.Text, out output))
    {
        MessageBox.Show("Enter valid int.");
        tb1.Text = "0";
    }
}

DataBinding に関する便利なリンク:

msdn.microsoft.com

tb2ここでは、現在選択されているユーザーを表示するために、TextBox のバインドとコンバーターを提供しますname

このクラスを名前空間に追加します。

using System;
using System.Globalization;
using System.Windows.Data;

namespace WpfApplicationTest
{
[ValueConversion(typeof(object), typeof(String))]
public class MyConverter : IValueConverter
{
    public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
    {
        string name = "";
        if (value != null)
        {
            User user = (User)value;
            name = user.Name;
        }
        else
        {
            name = "";
        }

        return name;
    }

    public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
    {
        return null;
    }
}
}

次に、これをウィンドウに追加します。

xmlns:myNamespace="clr-namespace:WpfApplicationTest"

<Window.Resources>
    <myNamespace:MyConverter x:Key="myConverter"/>
</Window.Resources>

次に、TextBox を次のように編集します。

<TextBox Name="tb2" Text="{Binding Path=SelectedItem, ElementName=Grid, Mode=OneWay, Converter={StaticResource myConverter}}"/>
于 2013-10-22T06:54:36.640 に答える