Eval Bind # 和= 笔记

本文详细介绍了ASP.NET中的各种代码块标记及其用途,包括<%%>、<%=%>、<%@%>、<%:%>和<%#%>的区别,以及Eval、Bind和DataBinder.Eval在数据绑定中的应用。同时,文章还提供了实例演示如何使用这些标记和方法。

1.<% %>用来绑定后台代码
如:

< %
for(int i=0;i<100;i++)
{
Reaponse.Write(i.ToString());
}
%>

2.<%# %> 是在绑定控件DataBind()方法执行时被执行,用于数据绑定

如: <%# Container.DataItem("title") %>

3.<%= %>用来绑定后台的变量或方法且有返回值 的,但此时的变量名或方法的访问修饰符为protectedpublic

如:<%=name%> <%=getstr()%>

4.evalbind
evalbind都是绑定datatable或者其他(集合,等)中的内容,那么他们有什么区别呢?
性能方面怎么样呢?eval有哪几种用法呢?

ASP.NET中的EvalDataBinder.Eval方法

bind是双向绑定,但需数据源可更改才能用。
ASP.NET 2.0改善了模板中的数据绑定操作,把v1.x中的数据绑定语法DataBinder.Eval(Container.DataItem, fieldname)简化为Eval(fieldname)
Eval方法与DataBinder.Eval一样可以接受一个可选的格式化字符串参数。
Eval语法与DataBinder.Eval的不同点在于,Eval会根据最近的容器对象(例如DataListItem)的DataItem属性来自动地解析字段,而DataBinder.Eval需要使用参数来指定容器。
由于这个原因,Eval只能在数据绑定控件的模板中使用,而不能用于Page(页面)层。当然,ASP.NET 2.0页面中仍然支持DataBinder.Eval,你可以在不支持简化的Eval语法的环境中使用它。

用法

<%# Bind("Name") %> //绑定字段
<%# Container.DataItemIndex + 1%> //实现自动编号
<%# Container.ItemIndex %> //Repeater自动编号
<%# DataBinder.Eval(Container.DataItem, "[n]") %>

通常使用的方法

<%# DataBinder.Eval(Container.DataItem, "ColumnName") %>
<%# DataBinder.Eval(Container.DataItem, "ColumnName", null) %>
<%# DataBinder.Eval(Container, "DataItem.ColumnName", null) %>

其他用法

<%# ((DataRowView)Container.DataItem)["ColumnName"] %>
<%# ((DataRowView)Container.DataItem).Row["ColumnName"] %>
<%# ((DataRowView)Container.DataItem)["adtitle"] %>
<%# ((DataRowView)Container.DataItem)[n] %>
<%# ((DbDataRecord)Container.DataItem)[0] %>
<%# (((自定义类型)Container.DataItem)).属性.ToString() %>//如果属性为字符串类型就不用ToString()了

Eval用法

DataBinder.Eval范例

<%# DataBinder.Eval(Container.DataItem, "IntegerValue", "{0:c}") %>

格式化字符串参數是可选的。如果忽略参数,DataBinder.Eval 返回对象类型的值。


<%= %>、<% %>、<%@ %>、<%:%><%# %>的区别

<%=%>

里面放的变量名,未经过encode

<%:%>

里面放的变量名,经过encode

<% %>

中间一般放函数或者方法,典型的asp程序写法。

<%#%> 

这里是数据的绑定 只能用在数据绑定控件中。

<%@ %> 

表示:引用

//Html.MyLable(sss); 生成后的代码为"<span>sss</span>" encode后的代码
        public static string MyLable(this HtmlHelper helper, string lbText)
        {
            return string.Format("<span>{0}</span>", lbText);
        }
 
        //Html.MyMvcHtmlStringLable(sss); 生成后的代码即为<span>sss</span>,通过查看微软的扩展方法后得出
        public static MvcHtmlString MyMvcHtmlStringLable(this HtmlHelper helper, string lbText)
        {
            string str= string.Format("<span>{0}</span>", lbText);
            return new MvcHtmlString(str);//可以避免前端生成encode编码后的代码
        

运行、获取后台代码或值。

<%%>之间可以写服务器端代码,比如

<% 
for(var i=0;i<10;i++){
//执行循环体
}
%>

又如

<% 
for(var i=0;i<10;i++){
%>
//执行循环体(此时循环体为html语言)
<%}
%>

<%=%>获取后台的变量值,比如后台一个session["ab"]="ab";前台<%=session["ab"]%>就能取到值;
<%:%><%=%>


C#页面前台<%%><%#%><%=%>

ASP.net前台绑定用的最多,今天小小总结一下。

1:<%#Eval("")%>

2:<%#Bind("")%>

3:<%=变量%>

1:<%#Eval("数据列")%> 主要用于需要进行更改的数据列

如:我需要将<%#Eval("性别")%> =1 ;将1转换成女。

首先在.CS文件中定义一个方法:

        /// <summary>
        /// 转换性别
        /// </summary>
        /// <param name="obj"></param>
        /// <returns></returns>
        public object ChangeSex(object obj)
        {
            if (obj.ToString() == "0")
            {
                return "男";
            }
            else 
            {
                return "女";
            }
        }

<%#ChangeSex(Eval("性别"))%>=

可以把这些公共的转换方法全部放到一个公共类文件中,进行调用之。调用方法为:

<%#命名空间.公共类名.方法名("列")%>

<%# Common.ChangeSex(Eval("性别"))%>

也可以进行时间截取

如1: <%# Eval("StartTime", "{0:yyyy-MM-dd}")%>

或者2: <%# Convert.ToDateTime(Eval("StartTime").ToString()).ToString("yyyy-MM-dd")%>

2:<%#Bind("数据列")%>

常见于GridView中的不需要进行处理的数据列绑定。

3:<%=变量%>

需要在后台.cs文件中声明一个public的变量

public string userInfo= "数据";

直接调用就OK了

但是我们一般不会这样直接写一个定值;

就需要这样写了:

 public string StrOrders
        {
            set
            {
                ViewState["Orders"] = value;
            }
            get
            {
                if (ViewState["Orders"] == null)
                {
                    ViewState["Orders"] = "";
                }
                return ViewState["Orders"].ToString();
            }
        }

这样就OK了。

import tkinter as tk from tkinter import simpledialog, messagebox, filedialog, Menu import time import threading import json import uuid import os from datetime import datetime # ======================== # 工具函数 # ======================== def render_html(content): content = content.replace("<br>", "\n") content = content.replace("<p>", "\n").replace("</p>", "") content = content.replace("<h1>", "\n🔥 ").replace("</h1>", "\n") content = content.replace("<h2>", "\n📌 ").replace("</h2>", "\n") return content def round_button(parent, text, command, bg="#0078d7", fg="white"): btn = tk.Label(parent, text=text, bg=bg, fg=fg, font=(&#39;Segoe UI&#39;, 10), padx=15, pady=6, relief="flat", cursor="hand2", borderwidth=0) btn.bind("<Button-1>", lambda e: command()) btn.bind("<Enter>", lambda e: btn.config(bg="#005a9e")) btn.bind("<Leave>", lambda e: btn.config(bg=bg)) return btn # ======================== # 主类:Win12 Ultra VM v9.0(优化版) # ======================== class Win12UltraVM_Optimized: def __init__(self, root): self.root = root self.root.title("🌤️ Advanced Electronic Display OS v9.0 - Optimized") self.root.geometry("1400x900") self.root.configure(bg="#f5f5f5") self.root.state(&#39;zoomed&#39;) # 全屏启动 # === 系统状态 === self.powered_on = False self.current_user = "User" self.clipboard = "" self.notification_log = [] self.open_windows = {} self.showing_app_drawer = False self.taskbar_apps = [] # 当前任务栏运行的应用 # 字体 self.font_ui = (&#39;Segoe UI&#39;, 10) self.font_code = (&#39;Consolas&#39;, 11) self.font_title = (&#39;Bahnschrift&#39;, 14, &#39;bold&#39;) self.font_small = (&#39;Segoe UI&#39;, 9) # 文件系统(模拟) self.fs_path = "virtual_fs.json" self.load_filesystem() # 启动动画 self.boot_animation() def load_filesystem(self): if os.path.exists(self.fs_path): try: with open(self.fs_path, &#39;r&#39;, encoding=&#39;utf-8&#39;) as f: data = json.load(f) self.filesystem = data.get("filesystem", { "/": ["Documents"], "/Documents": [] }) self.file_content = data.get("file_content", {}) self.recycle_bin = data.get("recycle_bin", {}) except: self.init_default_fs() else: self.init_default_fs() def init_default_fs(self): self.filesystem = { "/": ["Documents", "Downloads", "Pictures"], "/Documents": ["readme.txt"], "/Downloads": [], "/Pictures": [] } self.file_content = { "readme.txt": "欢迎使用 AE-OS v9.0\n这是一个可持久化的虚拟系统。" } self.recycle_bin = {} def save_filesystem(self): data = { "filesystem": self.filesystem, "file_content": self.file_content, "recycle_bin": self.recycle_bin } with open(self.fs_path, &#39;w&#39;, encoding=&#39;utf-8&#39;) as f: json.dump(data, f, ensure_ascii=False, indent=2) # ======================== # 1. 开机动画(Win12 概念风格) # ======================== def boot_animation(self): splash = tk.Toplevel(self.root) splash.overrideredirect(True) w, h = 600, 350 x = (self.root.winfo_screenwidth() - w) // 2 y = (self.root.winfo_screenheight() - h) // 2 splash.geometry(f"{w}x{h}+{x}+{y}") splash.configure(bg="white") canvas = tk.Canvas(splash, bg="white", highlightthickness=0) canvas.pack(fill=tk.BOTH, expand=True) rings = [] for i in range(4): x0, y0, x1, y1 = 250 + i * 25, 120, 290 + i * 25, 160 ring = canvas.create_oval(x0, y0, x1, y1, outline="#0078d7", width=6) rings.append(ring) label = tk.Label(splash, text="正在启动 Advanced OS v9.0...", fg="gray", bg="white", font=self.font_ui) label.place(relx=0.5, rely=0.7, anchor=tk.CENTER) self.animate_rings(canvas, rings, 0) self.root.after(3500, lambda: self.finish_boot(splash)) def animate_rings(self, canvas, rings, step): colors = ["#0078d7", "#e74856", "#107c10", "#ffb900"] for i in range(4): color = colors[(step + i) % 4] canvas.itemconfig(rings[i], outline=color) if step < 16: self.root.after(200, lambda: self.animate_rings(canvas, rings, step + 1)) def finish_boot(self, splash): splash.destroy() self.powered_on = True self.setup_desktop() # ======================== # 2. 主桌面 # ======================== def setup_desktop(self): self.clear_root() self.root.configure(bg="#f5f5f5") # --- 任务栏 --- taskbar = tk.Frame(self.root, bg="#e8e8e8", height=40) taskbar.pack(side=tk.TOP, fill=tk.X) taskbar.pack_propagate(False) start_btn = round_button(taskbar, "⊞ 开始", self.toggle_app_drawer, bg="#0078d7") start_btn.pack(side=tk.LEFT, padx=10, pady=5) time_label = tk.Label(taskbar, text="", fg="black", bg="#e8e8e8", font=self.font_ui) time_label.pack(side=tk.RIGHT, padx=15) self.update_time(time_label) # 运行中应用区 self.taskbar_apps_frame = tk.Frame(taskbar, bg="#e8e8e8") self.taskbar_apps_frame.pack(side=tk.RIGHT, padx=20) # --- 桌面图标区 --- desktop = tk.Frame(self.root, bg="#f5f5f5") desktop.pack(fill=tk.BOTH, expand=True, padx=40, pady=40) apps = [ ("📄 记事本", self.open_notepad), ("🌐 浏览器", self.open_browser), ("⚙️ 设置", self.open_settings), ("🧮 计算器", self.open_calculator), ("🗑️ 回收站", self.open_recycle_bin), ("📁 文件管理", self.open_file_manager), ("📦 应用商店", self.open_store), ("💬 AI助手", self.open_ai_assistant), ] for name, cmd in apps: self.create_icon(desktop, name, cmd) # --- 状态栏 --- self.status_bar = tk.Label(self.root, text=f"🟢 就绪 | 用户: {self.current_user}", bg="#efefef", fg="gray", font=self.font_small, anchor="w", height=2) self.status_bar.pack(side=tk.BOTTOM, fill=tk.X) self.status_bar.bind("<Button-1>", self.show_notifications) self.add_notification("系统已启动。欢迎使用 AE-OS v9.0") def update_time(self, label): if not self.powered_on: return label.config(text=time.strftime("%H:%M:%S")) self.root.after(1000, lambda: self.update_time(label)) def create_icon(self, parent, text, cmd): frame = tk.Frame(parent, width=100, height=100) frame.pack_propagate(False) frame.pack(side=tk.LEFT, padx=30, pady=30) label = tk.Label(frame, text=text, bg="white", fg="black", font=(&#39;Segoe UI Symbol&#39;, 10), relief="solid", bd=1, highlightbackground="#ddd", padx=5, pady=5, cursor="hand2") label.pack(fill=tk.BOTH, expand=True) label.bind("<Button-1>", lambda e: cmd() if e.num == 1 else self.show_context_menu(e, text)) label.bind("<Double-Button-1>", lambda e: cmd()) label.bind("<Enter>", lambda e: label.config(bg="#f0f0ff")) label.bind("<Leave>", lambda e: label.config(bg="white")) def show_context_menu(self, event, filename): menu = Menu(self.root, tearoff=0) menu.add_command(label="📋 复制名称", command=lambda: self.copy_text(filename)) menu.tk_popup(event.x_root, event.y_root) # ======================== # 3. 应用抽屉(开始菜单) # ======================== def toggle_app_drawer(self): if self.showing_app_drawer and hasattr(self, &#39;drawer&#39;) and self.drawer.winfo_exists(): self.drawer.destroy() self.showing_app_drawer = False else: self.drawer = tk.Toplevel(self.root) self.drawer.geometry("240x500+10+50") self.drawer.configure(bg="white") self.drawer.overrideredirect(True) self.drawer.attributes(&#39;-alpha&#39;, 0.98) title = tk.Label(self.drawer, text="📱 所有应用", bg="white", fg="#0078d7", font=self.font_title) title.pack(pady=10) for name, cmd in self.get_all_apps(): btn = round_button(self.drawer, name, cmd, bg="white", fg="black") btn.pack(fill=tk.X, pady=2, padx=10) self.showing_app_drawer = True def get_all_apps(self): return [ ("📄 记事本", self.open_notepad), ("🌐 浏览器", self.open_browser), ("⚙️ 设置", self.open_settings), ("🧮 计算器", self.open_calculator), ("🗑️ 回收站", self.open_recycle_bin), ("📁 文件管理", self.open_file_manager), ("📦 应用商店", self.open_store), ("💬 AI助手", self.open_ai_assistant), ("🔁 重启", self.reboot_system), ("⛔ 关机", self.shutdown_system), ] # ======================== # 4. 通用窗口管理 # ======================== def new_window(self, title, width=800, height=600): win = tk.Toplevel(self.root) win.title(title) win.geometry(f"{width}x{height}") win.configure(bg="white") frame = tk.Frame(win, bg="white", padx=15, pady=15) frame.pack(fill=tk.BOTH, expand=True) # 添加到任务栏 task_btn = round_button(self.taskbar_apps_frame, title.split()[0], lambda: win.lift(), bg="#f0f0f0", fg="black") task_btn.pack(side=tk.LEFT, padx=2) window_id = str(uuid.uuid4()) self.open_windows[window_id] = (win, lambda: self.close_window(window_id, task_btn)) win.protocol("WM_DELETE_WINDOW", lambda: self.close_window(window_id, task_btn)) return window_id, win, frame def close_window(self, wid, task_btn): if wid in self.open_windows: win, _ = self.open_windows[wid] win.destroy() task_btn.destroy() del self.open_windows[wid] # ======================== # 5. 记事本(支持保存) # ======================== def open_notepad(self): wid, win, frame = self.new_window("📄 记事本", 700, 500) text = tk.Text(frame, font=self.font_code, bg="white", fg="black", wrap=tk.WORD) text.pack(fill=tk.BOTH, expand=True) sb = tk.Scrollbar(text, command=text.yview) sb.pack(side=tk.RIGHT, fill=tk.Y) text.config(yscrollcommand=sb.set) menu = Menu(win) menu.add_command(label="💾 保存", command=lambda: self.save_file_dialog(text)) menu.add_command(label="📋 复制", command=lambda: self.copy_from_widget(text)) menu.add_command(label="✂️ 切除", command=lambda: self.cut_from_widget(text)) menu.add_command(label="📌 粘贴", command=lambda: self.paste_to_widget(text)) win.config(menu=menu) def save_file_dialog(self, widget): content = widget.get(1.0, tk.END).strip() fname = filedialog.asksaveasfilename( initialdir="/", title="保存文件", defaultextension=".txt", filetypes=[("Text files", "*.txt"), ("All files", "*.*")] ) if fname: with open(fname, &#39;w&#39;, encoding=&#39;utf-8&#39;) as f: f.write(content) self.add_notification(f"✅ 已保存到: {os.path.basename(fname)}") # ======================== # 6. 浏览器(带标签页) # ======================== def open_browser(self): wid, win, frame = self.new_window("🌐 浏览器", 900, 600) notebook = tk.Frame(frame, bg="white") notebook.pack(fill=tk.BOTH, expand=True) addr_frame = tk.Frame(notebook, bg="#f0f0f0", height=40) addr_frame.pack(fill=tk.X, pady=5) addr_frame.pack_propagate(False) url_var = tk.StringVar(value="about:start") entry = tk.Entry(addr_frame, textvariable=url_var, font=self.font_code) entry.pack(side=tk.LEFT, fill=tk.X, expand=True, padx=5) go_btn = round_button(addr_frame, "前往", lambda: self.load_page(url_var.get(), text_w), bg="#0078d7") go_btn.pack(side=tk.RIGHT, padx=5) text_w = tk.Text(notebook, bg="white", fg="black", font=self.font_code, wrap=tk.WORD) text_w.pack(fill=tk.BOTH, expand=True) self.load_page("about:start", text_w) def load_page(self, url, text_widget): if url == "about:start": content = "📘 欢迎使用 WinBrowse\n\n- 输入网址浏览\n- 使用 file:// 访问本地文件" elif url.startswith("file://"): fname = url[7:] content = self.file_content.get(fname, "❌ 文件未找到") else: content = f"🌐 正在访问: {url}\n\n此为模拟浏览器,无真实网络连接。" text_widget.config(state=tk.NORMAL) text_widget.delete(1.0, tk.END) text_widget.insert(tk.END, content) text_widget.config(state=tk.DISABLED) # ======================== # 7. 其他应用(略简) # ======================== def open_settings(self): self.simple_app("⚙️ 设置", "系统设置面板") def open_calculator(self): self.simple_app("🧮 计算器", "1+1=2") def open_store(self): self.simple_app("📦 应用商店", "暂无可用应用") def open_ai_assistant(self): self.simple_app("💬 AI助手", "AI 功能需接入模型 API") def simple_app(self, title, content): wid, win, frame = self.new_window(title) tk.Label(frame, text=content, font=self.font_code, fg="gray").pack(pady=20) def open_recycle_bin(self): wid, win, frame = self.new_window("🗑️ 回收站") lb = tk.Listbox(frame, font=self.font_code) lb.pack(fill=tk.BOTH, expand=True) for f in self.recycle_bin: lb.insert(tk.END, f) def open_file_manager(self): wid, win, frame = self.new_window("📁 文件管理器") lb = tk.Listbox(frame, font=self.font_code) lb.pack(fill=tk.BOTH, expand=True) for path, files in self.filesystem.items(): lb.insert(tk.END, f"[{path}]") for f in files: lb.insert(tk.END, f" 📄 {f}") # ======================== # 8. 电源控制 # ======================== def reboot_system(self): self.fade_out() self.root.after(600, self.do_reboot) def do_reboot(self): self.clear_root() self.boot_animation() self.root.after(3500, self.setup_desktop) def shutdown_system(self): self.fade_out() self.root.after(600, self.do_shutdown) def do_shutdown(self): self.save_filesystem() off = tk.Toplevel(self.root) off.overrideredirect(True) off.geometry(f"{self.root.winfo_screenwidth()}x{self.root.winfo_screenheight()}+0+0") off.configure(bg="black") tk.Label(off, text="👋 系统已关闭。你可以安全地关闭计算机。", fg="white", bg="black", font=(&#39;Segoe UI&#39;, 16)).place(relx=0.5, rely=0.5, anchor=tk.CENTER) self.root.after(3000, self.root.quit) def fade_out(self): for i in range(100, 0, -5): self.root.attributes(&#39;-alpha&#39;, i / 100) self.root.update() time.sleep(0.02) # ======================== # 9. 工具函数 # ======================== def clear_root(self): for widget in self.root.winfo_children(): widget.destroy() def add_notification(self, msg): t = datetime.now().strftime("%H:%M") self.notification_log.append(f"[{t}] {msg}") if len(self.notification_log) > 100: self.notification_log.pop(0) def show_notifications(self, event): win = tk.Toplevel(self.root) win.title("🔔 通知中心") win.geometry("400x300") win.configure(bg="white") lb = tk.Listbox(win, font=self.font_code, bg="white", fg="black") lb.pack(fill=tk.BOTH, expand=True, padx=10, pady=10) for msg in reversed(self.notification_log[-20:]): lb.insert(0, msg) def copy_from_widget(self, widget): try: selected = widget.get(tk.SEL_FIRST, tk.SEL_LAST) self.clipboard = selected except: pass def cut_from_widget(self, widget): self.copy_from_widget(widget) try: widget.delete(tk.SEL_FIRST, tk.SEL_LAST) except: pass def paste_to_widget(self, widget): if self.clipboard: widget.insert(tk.INSERT, self.clipboard) if __name__ == "__main__": root = tk.Tk() app = Win12UltraVM_Optimized(root) root.mainloop() 简单升级其他应用
最新发布
11-24
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值